该成员是非const,并且该成员的成员函数是非const,当它在const成员函数上调用时,它将生成错误,抱怨:
error: passing 'const foo' as 'this' argument discards qualifiers [-fpermissive]
码:
// this class is in library code i cannot modify it
class CWork {
public:
const string work(const string& args) { // non const
...
return "work";
}
};
// this is my code i can modify it
class CObject {
private:
CWork m_work; // not const
public:
const string get_work(const string& args) const { // const member function
return m_work.work(args); // error here
}
};
这是为什么以及如何解决这个问题?编译器是g ++ 5.3.1。
在const
方法内部,对象(*this
)及其所有成员都是const
。想一想,如果不是这样,那么const
这个对象就没有任何意义。
因此m_work
是const
内部的get_work
,你只能在它上面调用const
方法。
使work
也是const
方法。没有明显的理由让它不是const
,默认你应该制作方法const
。只有当你需要修改对象时才使它们成为非const
。
它在图书馆我无法改变它。
在那种情况下,你运气不好。你也只能使get_work
非const,因为work
似乎修改m_work
因此修改你的CObject
你不能用const
方法。