在 const 函数中的非常量成员上调用非常量函数

calling non-const function on non-const member in const function

成员是非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_workget_work 中是 const 并且你只能在它上面调用 const 方法。

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

it's in library i cannot change it.

那样的话你就不走运了。你也只能使 get_work 成为非 const,因为 work 似乎修改了 m_work 因此修改了你的 CObject,而你不能在 const 方法中这样做。