【发布时间】:2019-07-09 10:43:06
【问题描述】:
成员是非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。
【问题讨论】:
-
抱歉,get_work 是一个失败的 const 函数。
-
在 const 成员中
*this是 const。所以它所有的会员数据都太... -
m_work是const在get_work内 -
大声笑为什么所有的反对票,我问是因为我遇到了这个问题
-
因为首先你发布了与错误无关的错误代码,现在它相当不清楚问题是什么。您不能在
const对象上调用非 const 方法,这就是错误告诉您的...
标签: c++ g++ constants member-functions