显然,仍然允许const成员函数更改类成员指向的数据。这里是我的意思的一个例子:防止const成员函数更改成员数组
class MyClass
{
public:
MyClass();
int getSomething() const;
private:
int* data;
};
// ... data = new int[10];, or whatever
int MyClass::getSomething() const
{
data[4] = 3; // this is allowed, even those the function is const
return data[4];
}
我宁愿如果这是不允许的。我应该如何定义“数据”,以便“getSomething()const”不被允许改变它? (但是为了让非const函数可以改变它。)对于这种情况是否有某种“最佳实践”?也许std :: vector?
是的,事实证明,const成员函数没有你想象的那么有用。 –
@David:只有当他使用'std :: vector'而不是'int *'时,它才会变得有用。 –
Nawaz