可能重複:
why private value of the obj can be changed by class instance?爲什麼==超載可以訪問參數的私有成員
考慮以下(部分)代碼:
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
,但是不是這樣的訪問無效嗎?
出了什麼問題'回報g.id ==這個 - > id'? – sbi
在附註中,我認爲用戶名「WeaklyTyped」非常好地匹配了這個問題。 – datenwolf
@sbi - 它有一個不需要的'this->'。 –