错误原因
将“const xxx”作为“this”参数传递会丢弃限定符
当函数参数为const的对象,需要给函数添加限定符const,使函数不改变该对象内容。
修改前
class UserProfile{
public:
enum ulevel{base,middle,high,expert};
UserProfile() = default;
UserProfile(string login,ulevel = base);
bool operator!=(const UserProfile& rhs);
bool operator==(const UserProfile&);
//错误处
string login() {return _login;}
string user_name() {return _user_name;}
int login_count() {return _times_logged;}
int guess_count() {return _guesses;}
int guess_correct() {return _correct_guesses;}
double guess_average() const;
string level() const;
};
ostream& operator<<(ostream &os,const UserProfile& rhs)
{
os<<rhs.login()<<" "
<<rhs.level()<<" "
<<rhs.login_count()<<" "
<< rhs.guess_count() << ' '
<< rhs.guess_correct() << ' '
<< rhs.guess_average() << endl;
return os;
}
修改后
(给对应的类成员函数添加const限定符)
class UserProfile{
public:
enum ulevel{base,middle,high,expert};
UserProfile() = default;
UserProfile(string login,ulevel = base);
bool operator!=(const UserProfile& rhs);
bool operator==(const UserProfile&);
//错误处
string login() const {return _login;}
string user_name() const {return _user_name;}
int login_count() const {return _times_logged;}
int guess_count() const {return _guesses;}
int guess_correct() const {return _correct_guesses;}
double guess_average() const;
string level() const;
};
来源:CSDN
作者:hey_jude1719
链接:https://blog.csdn.net/qq_40016998/article/details/104816382