const 修饰This指针

 在C++中经常会见到函数后面跟着const修饰,如下:

class Test
{
public:
	Test(int a,int b)//实质是Test(Test *this,int a,int b)
	{
		this->a = a;
		this->b = b;
	}
	void printT()
	{
		cout<<"a:"<<this->a<<endl;
		cout<<"b:"<<this->b<<endl;
	}
	//1 const 写在什么位置 没有关系
	//2 const 修饰的是谁?
	//3 const 修饰的是形参 a、b 吗?--不是
	//4 const 修饰的是属性 this->a this->b?--不是
	//实质是:void  OpVar(const Test *this int a,int b) 
	//void  OpVar(const Test *const this int a,int b) 更精确的写法
	//const 修饰的是this指针,this指针指向的内存的空间不能修改
	void  OpVar(int a,int b) const //一般写在后边
	{
		this->a = 100;
		this->b = 100;
	}
protected:
private:
	int a;
	int b;
};

这个const 修饰的是this指针,表示this指针指向的内存空间不能修改,因此,在上面的代码中函数OpVar试图修改this指针指向的对象的属性,这样C++编译器会编译不过去的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

洪流之源

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

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

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

打赏作者

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

抵扣说明:

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

余额充值