错误:将'const ...'传递为'...'的'this'参数会丢弃调用方法中的限定符

yay*_*yuj 3 c++ member-functions

我将一个对象的引用传递给一个函数,我使用const来表示它是只读方法,但如果我在该方法中调用另一个方法,则会发生此错误,即使我没有将引用作为参数传递.

错误:将'const A'作为'void A :: hello()'的'this'参数传递,丢弃限定符[-fpermissive]

错误:将'const A'作为'void A :: world()'的'this'参数传递,丢弃限定符[-fpermissive]

#include <iostream>

class A
{
public:
    void sayhi() const
    {
        hello();
        world();
    }

    void hello()
    {
        std::cout << "world" << std::endl;
    }

    void world()
    {
        std::cout << "world" << std::endl;
    }
};

class B
{
public:
    void receive(const A& a) {
        a.sayhi();
    }
};

class C
{
public:
    void receive(const A& a) {
        B b;
        b.receive(a);
    }
};

int main(int argc, char ** argv)
{
    A a;
    C c;
    c.receive(a);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Cor*_*mer 10

既然sayhi()const,那么它所调用的所有函数也必须声明const,在这种情况下hello()world().您的编译器会警告您有关const的正确性.