C++ 错误:将 'const ...' 作为 '...' 的 'this' 参数传递会丢弃限定符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26963510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:42:42  来源:igfitidea点击:

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

c++

提问by yayuj

error: passing 'const A' as 'this' argument of 'void A::hi()' discards qualifiers [-fpermissive]

错误:将“const A”作为“void A::hi()”的“this”参数传递会丢弃限定符 [-fpermissive]

I don't understand why I'm getting this error, I'm not returning anything just passing the reference of the object and that is it.

我不明白为什么我会收到这个错误,我没有返回任何东西,只是传递了对象的引用,就是这样。

#include <iostream>

class A
{
public:
    void hi()
    {
        std::cout << "hi." << std::endl;
    }
};

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

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;
}

@edit

@编辑

I fixed it using const correctness but now I'm trying to call methods inside of the same method and I get the same error, but the weird thing is that I'm not passing the reference to this method.

我使用 const 正确性修复了它,但现在我试图在同一个方法中调用方法,但我得到了同样的错误,但奇怪的是我没有传递对这个方法的引用。

#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;
}

error: passing 'const A' as 'this' argument of 'void A::hello()' discards qualifiers [-fpermissive]

error: passing 'const A' as 'this' argument of 'void A::world()' discards qualifiers [-fpermissive]

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

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

回答by therealrootuser

Your himethod is not declared as constinside your A class. Hence, the compiler cannot guarantee that calling a.hi()will not change your constant reference to a, thus it raises an error.

您的hi方法未const在 A 类中声明。因此,编译器无法保证调用a.hi()不会更改您对 的常量引用a,从而引发错误。

You can read more about constant member functions hereand correct usage of the constkeyword here.

你可以阅读更多关于常量成员函数在这里和正确使用const关键字这里