今天我重新阅读了《C++ Primer(第四版)》中关于成员函数和const引用等部分,并写出了这个奇怪的小程序:
using std::cout;
using std::endl;
class ConstCheater
{
public:
ConstCheater(int avalue) : ccp(this), value(avalue) {}
ConstCheater& getccp() const {return *ccp;}
int value;
private:
ConstCheater* ccp;
};
int main()
{
const ConstCheater cc(7); //Initialize the value to 7
cout << cc.value << endl;
cc.getccp().value = 4; //Now setting it to 4, even though it's const!
cout << cc.value << endl;
cc.value = 4; //This is illegal
return 0;
}
我的问题是——为什么C++允许这样的语法?当一个类被声明为const时,为什么我可以编辑普通的数据成员?难道const的目的不是为了使其值不能被修改吗?