大家好,我是阿林。今天我和大家分享的内容是c++中的const的修饰的对象的内容。
我想提出一个问题,我定义的void opVar(int a, int b) const这个函数中const修饰的是谁。
其实const 修饰的是既不是形参a也不是形参b 而是修饰的是属性this->a this->b。下面我我们就痛代码去测试一下相关的结论吧。
#include <iostream>
using namespace std;
class Test
{
public:
Test(int a,int b)
{
this->a = a;
this->b = b;
}
void printT()
{
cout << "a; " << a << endl;
cout << " b: " << b << endl;
}
//1 const 写在什么位置 没关系
//2 const 修饰的是谁?
//const 修饰的是形参a 不是
//const 修饰的是属性this->a this->b
void opVar(int a, int b) const // 等价为 void opVar(const Test *this,int a,int b)
{
a = 100; //能够运行代表const不是修饰啊;
//this->a = 100; //编译器报错证明是不可修改的,所以修饰this->a this->b
cout << "a:" << a << endl;
cout << "b: " << this->b << endl;
}
private:
int a;
int b;
};
int main()
{
system("pause");
return 0;
}