【发布时间】: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]
【问题讨论】:
-
hi是非const成员函数;a是const。 -
传递意味着作为(隐式)参数。与返回无关。
标签: c++