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

error: passing 'const …' as 'this' argument of '…' discards qualifiers in calling method

本文关键字:方法 调用 参数传递 const 作为 this 错误      更新时间:2023-10-16

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

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

错误:将"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;
}

既然sayhi()const,那么它调用的所有函数也必须声明为const,在本例中为hello()world()。您的编译器正在警告您有关恒定正确性的信息。