如何在c ++中丢弃const

yeg*_*256 2 c++ const

这就是我想要做的事情,我不能:

#include <string>
using namespace std;
class A {
public:
  bool has() const { return get().length(); }
  string& get() { /* huge code here */ return s; }
private:
  string s;
};
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

passing ‘const A’ as ‘this’ argument of
‘std::string& A::get()’ discards qualifiers
Run Code Online (Sandbox Code Playgroud)

我明白问题是什么,但我该如何解决呢?我真的需要has()const.谢谢.

Eam*_*nne 6

添加第二个重载get():

string const & get() const { return s; }
Run Code Online (Sandbox Code Playgroud)

这将在const类的类型对象上调用A.

在实践中,我更喜欢 添加const-typed访问器,然后将修改完全保留在类内部,甚至完全避免它们.例如,这意味着有一个方法DoUpdateLabel(){/*do something with s*/}而不是暴露内部.这有很好的副作用,你可以避免在许多情况下重复访问器.

如果您绝对必须通过访问器进行修改,并且您也不需要额外的const包装器,则可以使用const_cast<>:

bool has() const { return const_cast<A*>(this)->get().length(); }
Run Code Online (Sandbox Code Playgroud)

但是,如果get()有副作用并且has()被宣布const,那么这是否是你真正想要的行为是值得怀疑的.