错误:将“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]
hi
是一个非const
成员函数;a
是const
。 - Oliver Charlesworth