我是第一次使用 gcc(以前是 msvc),现在我在返回对我的类中的变量的引用时遇到了一些问题。这是代码:
class Foo
{
public:
const int& getMyVar() const
{
return mMyVar;
}
private:
int mMyVar;
};
如果有比简单 int 更大的数据结构,我无法想象我必须返回拷贝而不是引用。
这是编译错误:
error: invalid initialization of reference of type 'int&' from expression of type 'int'
如果你能帮助我并告诉我如何解决我的问题,那就太好了。
最佳答案
给定以下代码,它是您的类的一个小变体(添加了构造函数;在类后添加了分号)和一个简单的 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;
}
关于c++ - 返回对属性的引用 (GCC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17647971/