【问题标题】:calling non-const function on non-const member in const function在 const 函数中的非常量成员上调用非常量函数
【发布时间】: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 constget_work
  • 大声笑为什么所有的反对票,我问是因为我遇到了这个问题
  • 因为首先你发布了与错误无关的错误代码,现在它相当不清楚问题是什么。您不能在 const 对象上调用非 const 方法,这就是错误告诉您的...

标签: c++ g++ constants member-functions


【解决方案1】:

const 方法中,对象 (*this) 及其所有成员都是 const。想想看,如果不是这种情况,那么 const 的对象就没有任何意义。

因此m_workget_work 中是const,您只能在其上调用const 方法。

使work 也成为const 方法。没有明显的理由让它不是const,默认情况下你应该创建方法const。仅当您需要修改对象时才使它们成为非const

它在图书馆里,我不能改变它。

在这种情况下,你很不走运。您也只能使 get_work 非 const,因为 work 似乎修改了 m_work 因此修改了您的 CObject ,这是您在 const 方法中无法做到的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 2019-11-20
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多