看板 C_and_CPP 關於我們 聯絡資訊
※ 引述《tyc5116 (累人啊....)》之銘言: : 不好意思喔,再問一下,我了解Q大所說的是什麼,但我還是不知道為何我這樣寫不行 : 再一個類似的例子 : class TableA{ : public: : TableA(int vAID,string vName); : void SetAID(int vID); : int& GetAID(); 這個函式會回傳 reference to int, 而且可能會修改到物件的內容 (non-const) : void SetName(string vName); : string& GetName(); 同前面的 GetAID() : bool operator==(const TableA& vTableA) const; 這個函式比較自己和另一個物件, 因為不會改變物件的內容,所以宣告為 const : private: : int AID; : string Name; : }; : 而operator的實作為 : bool TableA::operator ==(const TableA& vTableA) const{ : return (this->AID == vTableA.AID) && (this->Name==vTableA.Name); : } OK,因為 int 和 string 使用 == 做比較時,並不會改變其內容 所以 TableA::operator== 可以宣告為 const 但如果你這樣寫呢? bool TableA::operator==(const TableA& vTableA) const { return (AID == vTableA.GetAID()) && (Name==vTableA.GetName()); } OK,你沒有改變 AID 和 Name 的內容,所以 operator== 是可以宣告成 const, 但另一個參數 vTableA 呢?你說它是 const,但又對它呼叫 GetAID() 和 GetName(), 而這兩個函式,你並不保證它們不會改變 vTableA。 常見的做法如下: class TableA { public: int& GetAID() { return AID; } const int& GetAID() const; { return AID; } bool operator==(const TableA& vTableA) const { // 這行會自動呼叫 const 版本的 GetAID(), // 因為 vTableA 被宣告為 const return AID==vTableA.GetAID(); } private: int AID; }; -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.29.108
tyc5116:了解,謝謝 09/07 18:11
sponge0121:對厚 回傳的type也要是const 我忘記了 囧 09/07 20:45