const与this指针

const是一个C语言(ANSI C)的关键字,具有着举足轻重的地位。它限定一个变量不允许被改变,产生静态作用。使用const在一定程度上可以提高程序的安全性和可靠性。另外,在观看别人代码的时候,清晰理解const所起的作用,对理解对方的程序也有一定帮助。

形式参数后加const

#if 0
class object
{
public:
	int* ptr;
	int val;
public:
	object(int* p) :ptr(p) {}
	int* getp() const //const object *const this

	{
		this->val = 100;//error
		ptr = nullptr;//error this->ptr=nullptr  不让改
		*ptr = 200;//ok
		return ptr;
	}


};
int main()
{
	int tmp = 10;
	object obj(& tmp);
	object objb(&tmp);
	obj.getp();//obj(this);
	return 0;
}
#endif


#if 0
class object
{
public:
	int* ptr;
	int val;
public:
	object(int* p) :ptr(p) {}
	const int* getp()   // object *const this

	{
		this->val = 100;//ok
		ptr = nullptr;//ok
		return ptr;
	}


};


int main()
{
	int tmp = 10;
	object obj(&tmp);
	object objb(&tmp);
	const int *p=obj.getp();//obj(this);
	//int* p = obj.getp();//error 

	return 0;
}
#endif

以引用返回

#if 1
class object
{
public:
	int* ptr;
	int val;
public:
	object(int* p) :ptr(p) {}
	 int*const & getp() const  //  int* & getp() const  return ptr会报错! // 

	{
		//this->val = 100;//ok
		//ptr = nullptr;//ok
		return ptr;
	}
};
int main()
{
	int tmp = 10;
	int x = 20;
	object obj(&tmp);
	object objb(&tmp);
	//const int* p = obj.getp();//obj(this);
	int* p = obj.getp();//error 
	p = &x;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值