首页 > 代码库 > discards qualifier

discards qualifier

C++中,引用const对象时,也只能通过该对象访问其const函数,因为非const函数可能修改const对象本身,编译器避免了这一类情况会报错如下:

passing const Sales_data as this argument of  std::string Sales_data::isbn() discards qualifiers [-fpermissive]

源代码:

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的才能够编译通过

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();}

 

discards qualifier