类c ++中的访问器函数

tin*_*s91 1 c++ const accessor

例如,我有一个类的访问函数:

class A {
 public:
 int a; 
 int& getA() const; 
}; 

int& A::getA () const {
 return a;  // error: invalid initialization of reference of type 'int&' from expression of type 'const    //                    int'
 }
Run Code Online (Sandbox Code Playgroud)

问题是:1.数据成员'a'不是'const int'类型,为什么错误呢?
2.当我将返回类型更改为int时,它也可以.为什么?

Jac*_*ack 6

因为你指定的getA()const.const从声明为的方法返回对成员变量的非引用const将允许修改引用的值.

如果您想要一个只读访问器,那么只需将访问器声明为

const int& A::getA() const
Run Code Online (Sandbox Code Playgroud)

否则你必须从方法中删除constness.

int允许将返回的值转换为a,因为您不再返回引用,但是副本a因此无法修改原始成员变量.

请注意,您可以同时使用它们:

int& getA() { return a; }
const int& getA() const { return a; }
Run Code Online (Sandbox Code Playgroud)