C++中,引用const對象時,也只能經過該對象訪問其const函數,由於非const函數可能修改const對象自己,編譯器避免了這一類狀況會報錯以下:函數
passing 'const Sales_data' as 'this' argument of 'std::string Sales_data::isbn()' discards qualifiers [-fpermissive]
源代碼:this
class Sales_data{ friend bool compareIsbn(const Sales_data &lhs,const Sales_data &rhs); string bnum; string bname; public: Sales_data(string bnum,string bname):bnum(bnum),bname(bname){} string isbn() { return this->bnum; } }; bool compareIsbn(const Sales_data &lhs,const Sales_data &rhs){ return lhs.isbn()<rhs.isbn(); }
conpareIsbn由於調用的是const對象,訪問它的isbn()函數也必須是const的纔可以編譯經過spa
class Sales_data{ friend bool compareIsbn(const Sales_data &lhs,const Sales_data &rhs); string bnum; string bname; public: Sales_data(string bnum,string bname):bnum(bnum),bname(bname){} string isbn() const{ return this->bnum; } }; bool compareIsbn(const Sales_data &lhs,const Sales_data &rhs){ return lhs.isbn()<rhs.isbn(); }