在对象/成员函数的上下文中理解const的含义时遇到了一些问题。
参见例如此代码:
class Test
{
public:
Test():a(0), b(new int){}
int& get_a() const {return a;}
int* get_b() const {*b = 5; return b;}
private:
int a;
int *b;
};
int main()
{
Test t;
t.get_a();
t.get_b();
return 0;
}
我认为函数签名末尾的const表示:此函数不会改变对象的状态。
所以我期待int * get_b()的一个错误,因为它改变了对象。然而编译器抱怨这个:
error: binding 'const int' to reference of type 'int&' discards qualifiers
int& get_a() const {return a;}
那么为什么我不会因为没有改变任何东西而得到错误,get_a()只返回a,而不是get_a函数体中对象的更改。
感谢您提供任何帮助。