【问题标题】:error: passing 'const …' as 'this' argument of '…' discards qualifiers错误:将 'const ...' 作为 '...' 的 'this' 参数传递会丢弃限定符
【发布时间】:2015-01-13 19:45:09
【问题描述】:

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

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

#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 正确性修复了它,但现在我尝试在同一个方法中调用方法,我得到了同样的错误,但奇怪的是我没有传递对这个方法的引用。

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

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

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

【问题讨论】:

标签: c++


【解决方案1】:

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

您可以阅读更多关于常量成员函数hereconst 关键字here 的正确用法。

【讨论】:

  • 我改成了void hi() const,现在它可以工作了。这样对吗?一个具有 const 正确性的 void?
  • 是的。 const 告诉编译器该函数内部不会发生任何变化。返回类型与此无关
  • 在这种情况下,由于a.hi() 不会更改对象,因此这是正确的。它还有助于告知其他程序员这是一个“只读”方法,并且保证不会以任何方式改变对象。
  • constvoid hi() 之后适用于隐式A* this(因此使其成为const A* this),而不是返回类型。
【解决方案2】:
  1. 如前所述,一种选择是使 hi 方法为 const-qualified。

  2. 另一种选择是在调用 hi 方法时使用 const_cast,像这样

A& ref = const_cast <A&>(a);
ref.hi();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    相关资源
    最近更新 更多