【发布时间】:2010-05-26 11:26:23
【问题描述】:
这是我正在尝试做的,但我做不到:
#include <string>
using namespace std;
class A {
public:
bool has() const { return get().length(); }
string& get() { /* huge code here */ return s; }
private:
string s;
};
我得到的错误是:
passing ‘const A’ as ‘this’ argument of
‘std::string& A::get()’ discards qualifiers
我了解问题所在,但我该如何解决?我真的需要has() 成为const。谢谢。
【问题讨论】:
-
只是为了提醒你可变成员可以被 const one 修改,所以即使它必须修改 s在巨大的代码中。
-
get 有什么副作用?
-
显然修改了s。否则,微不足道的修复是
return s.length()。因此,has()不是 const。