例如我有一个类的访问器函数:
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'
}
问题是:
1. 数据成员'a'不是'const int'类型,为什么会报错?
2. 此外,当我将返回类型更改为 int 时,它也有效。为什么?
最佳答案
因为您指定 getA()
是 const
。从声明为 const
的方法返回对成员变量的非 const
引用将允许修改引用的值。
如果您想要一个只读访问器,那么只需将访问器声明为
const int& A::getA() const
否则,您必须从方法中删除常量。
将返回值转换为 int
是允许的,因为您不再返回引用,而是 a
的拷贝,因此无法修改原始成员变量。
请注意,您可以同时使用它们:
int& getA() { return a; }
const int& getA() const { return a; }
关于c++ - c++ 类中的访问器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26917441/