错误:传递'const ...'as'this'参数'...'丢弃限定符 [英] error: passing 'const …' as 'this' argument of '…' discards qualifiers

查看:111
本文介绍了错误:传递'const ...'as'this'参数'...'丢弃限定符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


错误:传递'const A'as'this'参数'void A :: hi()'丢弃
限定符[-fpermissive]

error: passing 'const A' as 'this' argument of 'void A::hi()' discards qualifiers [-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

我使用const正确性修复它,但现在我试图调用相同的方法内的方法,我得到相同的错误,但奇怪的是,我没有传递引用

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.

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




this'argument''void A :: hello()'
丢弃限定符[-fpermissive]

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

错误:传递const A 'void A :: world()'
丢弃限定符[-fpermissive]

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


推荐答案

您的 hi 方法在A类中未声明为 const 。因此,编译器不能保证调用 a.hi()不会改变对 a 的常量引用,产生错误。

Your hi method is not declared as const inside 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.

您可以阅读更多关于常量成员函数的信息此处并正确使用 const 关键字此处

You can read more about constant member functions here and correct usage of the const keyword here.

这篇关于错误:传递'const ...'as'this'参数'...'丢弃限定符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆