错误:传递' const ...'作为'这个' ' ...'的论点丢弃调用方法中的限定符

时间:2014-11-17 12:31:56

标签: c++ member-functions

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

  

错误:传递' const A'作为'这个'参数' void A :: hello()'抛弃限定符[-fpermissive]

     

错误:传递' const A'作为'这个' ' void A :: world()'抛弃限定符[-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;
}

1 个答案:

答案 0 :(得分:10)

由于sayhi()const,因此其调用的所有函数也必须声明为const,在本例中为hello()world()。您的编译器警告您const-correctness

相关问题