gpt4 book ai didi

c++ - 错误 : passing 'const …' as 'this' argument of '…' discards qualifiers in calling method

转载 作者:太空狗 更新时间:2023-10-29 19:52:22 36 4
gpt4 key购买 nike

我将一个对象的引用传递给一个函数,我使用 const 来指示它是只读方法,但是如果我在该方法内部调用另一个方法,即使我没有传递引用作为参数。

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]

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

最佳答案

既然sayhi()const,那么它调用的所有函数也必须声明为const,在本例中是hello( )world()。您的编译器警告您 const-correctness .

关于c++ - 错误 : passing 'const …' as 'this' argument of '…' discards qualifiers in calling method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26972808/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com