可能重复:
为什么类实例可以更改 obj 的私有值?
考虑以下(部分)代码:
class Group {
private:
int id;
public:
void set_id(int);
int get_id();
bool operator==(const Group&);
};
bool Group::operator==(const Group& g) {
if(g.id == this->id) { /* id is private? */
return true;
}
return false;
}
代码编译并且结果似乎正确。但是,在if
运算符重载实现的部分,我们直接访问了它的参数的私有成员 - const Group& g
,但是这样的访问不是无效的吗?