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++编译器会编译不过去的。

猜你喜欢

转载自blog.csdn.net/weicao1990/article/details/81626355
今日推荐