static静态方法和const方法

static:
1–类的静态成员为其所有对象共享,不管有多少对象,静态成员只有一份存于公用内存中。
2–静态函数或者静态的方法都是不存在This指针的,重点就在这个This指针上面。
3–普通方法可以调用静态方法;但是静态方法没法访问普通方法。
const:
void fun(const Test &t)const
{…}
第一个const是保护所传的参数不被修改,第二个const是说明该方法是常方法,常方法表示在这个方法或者函数的内部的数据成员进行修改。
/
如果一个方法不需要改变其参数,那咱们将其设置成常方法,反之设置成普通方法;
一般方法可以调用常方法;
常方法无法调用一般方法。
int a=10;
const int &b=a;
定义一个变量a我们可以用不可改变的b去引用a
const int a=10;
int &b=a;
定义一个常量a我们不可以用变量去引用a。

附代码:

#include<iostream>
using namespace std;

class Test
{
	friend void fun(Test &);
public:
	Test(int d=0):data(d)
	{
		count++;
	}
	~Test()
	{
		count--;
	}
	//void print(const Test*const this)
	void print()const
	{
		show();
	}
public:
	//void list(Test*const this)
	void list()
	{
		cout<<"This is list()"<<endl;
		data=0;

	}
	//void list(const Test*const this)
	void list()const//常方法
	{
		cout<<"This is list()const"<<endl;
		//data=0;//此处当改变data的值时会出现编译错误
	}
public:
	int GetData()const
	{
		return data;
	}
private:
	int data;
	static int count;
};
int Test::count=0;//对count 进行初始化

void fun(Test &t)
{
	cout<<"t.data="<<t.data<<endl;
	cout<<"object count="<<Test::count<<endl;
}
void main()
{
	Test t(100);
	Test t1(200);
	fun(t);
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力做一个code杠精

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值