在const函数中调用非const成员的非const函数

问题描述 投票:-3回答:1

该成员是非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。

c++ g++ const member-functions
1个回答
1
投票

const方法内部,对象(*this)及其所有成员都是const。想一想,如果不是这样,那么const这个对象就没有任何意义。

因此m_workconst内部的get_work,你只能在它上面调用const方法。

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

它在图书馆我无法改变它。

在那种情况下,你运气不好。你也只能使get_work非const,因为work似乎修改m_work因此修改你的CObject你不能用const方法。

© www.soinside.com 2019 - 2024. All rights reserved.