错误:将“const…”作为“this”参数传递给“…”会丢弃限定符。

99

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

@编辑

我使用了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]


3
hi 是一个非 const 成员函数;aconst - Oliver Charlesworth
1
将函数参数作为(隐式)参数传递。与返回无关。 - Deduplicator
4
可能是error: passing xxx as 'this' argument of xxx discards qualifiers的重复问题。 - Thirupathi Thangavel
3个回答

118

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

您可以在这里了解有关常量成员函数的更多信息,以及const关键字的正确使用方式,请参阅此处


4
我改成了void hi() const,现在它工作了。这样做对吗?一个带有常量正确性的void函数? - yayuj
6
是的,const关键字告诉编译器在该函数内部不会有任何改变。返回类型与此无关。 - Eric
3
在这种情况下,由于a.hi()不改变对象,因此这是正确的。这还有助于告诉其他程序员这是一个“只读”方法,并保证不以任何方式改变对象。 - therealrootuser
1
void hi() 后面的 const 应用于隐式的 A* this(因此使其成为 const A* this),而不是返回类型。 - Mike DeSimone

2
// **const object can call only const member function()** 

// **Modified Code**

#include <bits/stdc++.h>
using namespace std;

class A {
public:
    void hi() const {
        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() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
    #endif

    A a;
    C c;
    c.receive(a);

    return 0;
}

1
在 Stack Overflow 上鼓励使用 #include <bits/stdc++.h> 实际上是在寻求负评。为什么不应该使用 #include <bits/stdc++.h>? - Adrian Mole

0
  1. 如前所述,一种选择是将 hi 方法设为 const 限定符。

  2. 另一种选择是在调用 hi 方法时使用 const_cast,如下所示:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接