成员函数的const究竟修饰的是谁

demo

<pre name="code" class="cpp">class Test
{
public:
	const void OpVar(int a, int b)
	{
		a = 100;
	}
protected:
private:
};

Test类中有一个成员函数OpVar。有一个const修饰符也能够写成下两种形式

class Test
{
public:
	void const OpVar(int a, int b)
	{
		a = 100;
	}
protected:
private:
};


class Test
{
public:
	void OpVar(int a, int b)const
	{
		a = 100;
	}
protected:
private:
};
const放在了三个位置,都能够,并且效果也都一样,能够通过分别在成员函数中改动a,b,this->a, this->b,来測试。结果是const的作用是this->a和this->b。

原因:

const实际修饰的是隐藏的this指针。就像

void OpVar(const Test *, int a, int b)
这样也说明了为什么在之前的demo中const能够放在三个位置。由于const修饰的是隐藏的this指针。不能显示的写出来这个修饰关系,就放在外面,放在三个位置都能够。编译器都能认出来这是修饰this指针的。






原文地址:https://www.cnblogs.com/cxchanpin/p/6736875.html