给定以下代码,这是您的类的一个小变体(添加了构造函数;在类后添加了分号)和一个简单的main()
,我得到了编译错误:
z1.cpp: In function ‘int main()’:
z1.cpp:19:26: error: invalid initialization of reference of type ‘int&’ from expression of type ‘const int’
第 19 行是该const int &v2 = f.getMyVar();
行。删除参考标记,就可以了。
class Foo
{
public:
Foo(int n = 0) : mMyVar(n) {}
const int& getMyVar() const
{
return mMyVar;
}
private:
int mMyVar;
};
int main()
{
Foo f;
int v1 = f.getMyVar(); // Copies result
int &v2 = f.getMyVar(); // Error: must be const
const int &v3 = f.getMyVar(); // OK as long as there's a default constructor
return v1 + v2 + v3;
}