我认为你的问题有点含糊。
您有:
bool has() const { return get().length(); }
string& get() { /* huge code here */ return s; }
...,需要has()
是const
。
我能想到的三种方式来解决这个问题,这取决于你实际上要做的:
最干净的办法是,has
只使用const
代码。如果你的/* huge code here */
代码非const,但实际上并没有改变该类的逻辑值(例如计算一个缓存的内部值)考虑在涉及的数据上使用mutable
。
如果/* huge code here */
部分非const自然,考虑重构它变成一个不同的功能并分别称之为:
using namespace std;
class A {
public:
bool has() const { return get().length(); }
const string& get() const { return s; }
void computestuff() { /* huge code here */ }
private:
string s;
};
A instance;
// old client code:
// string s = instance.get();
//
// new code:
instance.computestuff(); // non-const call
instance.get(); // const call
instance.has(); // const call
最后,您还可以投的常量性远(但请记住,需要这样做几乎总是设计不良/需要重构的标志):
class A {
public:
bool has() const { return const_cast<A*>(this)->get().length(); }
string& get() { /* huge code here */ return s; }
private:
string s;
};
只是为了提醒您,可变成员可以通过const one,s o get()const(但可能不会返回一个非const ref)是有意义的,即使它必须在那里修改巨大的代码。 – AProgrammer 2010-05-26 11:51:56
有什么样的副作用? – 2010-05-26 11:52:27
它明显修改s。否则,这个简单的修复就是'return s.length()'。因此,'has()'不是const。 – MSalters 2010-05-26 15:19:54