什么情况
如果写出如下代码
class A
{
public:
A(int h = 0) : height(h) {}
int getHeight() { return height; }
private:
int height;
};
int main(int argc, char* argv[])
{
const A a;
int height = a.getHeight();
return 0;
}
用gcc编译就会报passing ‘const A’ as ‘this’ argument discards qualifiers [-fpermissive]
原因
因为对象a被const修饰, 表示该对象无法被修改, 但是A::getHeight()并没有const后缀修饰, 导致编译器认为该函数可能会有修改对象的可能. 因为编译器报此错误. 如果确认只是getter函数且不修改数据, 将成员函数已const后缀修饰即可消除该错误.