Cro*_*oll -1 c++ return reference return-type return-value
函数get1()和get2()的用法有什么不同?
struct x
{
float get1() const
{
float fx = 4;
fx += 1.5f;
return fx;
}
float& get2() const
{
float fx = 4;
fx += 1.5f;
return fx;
}
};
int main()
{
x t;
float x1 = t.get1();
float/*&*/ x2 = t.get2();
cout << x1 << endl;
cout << x2 << endl;
cin.get();
}
Run Code Online (Sandbox Code Playgroud)
据我所知,get2()只能是const类成员..我不完全清楚.如果有人可以指出我的参考或只是一个简短而完整的解决方案,那就太好了.
在您的情况下,get2()调用未定义的行为,因为您返回对超出范围的方法本地的引用.
不同之处在于返回float返回float值,同时float &返回对a的引用float.该引用可用于改变指示对象的数据; 按价值返回时,您只需获得一份副本.
听起来你只是对引用的内容感到困惑,所以这里是口语定义:引用是对象的另一个名称.这意味着引用要求其目标的存在存在于其他地方,非常类似于(非空)指针.
让我写一个更好的例子来说明差异:
struct x
{
x() : data(0) { }
float get1() const
{
return data;
}
// Cannot be const now, because we can't return a non-const reference to what
// would be a const data member. (If this method were const then data would be a
// const float, and that cannot bind to float &.)
float & get2()
{
return data;
}
private:
float data;
};
Run Code Online (Sandbox Code Playgroud)
现在我们有两个方法,一个返回data,另一个返回对它的引用.这里的区别在于get2()您可以实际更改以下值x::data:
x an_x;
float a = an_x.get1(); // a is 0
a = 5; // a is 5, an_x.data is still 0
a = x.get1(); // a is 0 again, because an_x.data did not change
float & b = an_x.get2(); // b is 0
b = 5; // b is 5, and so is an_x.data!
a = x.get1(); // a is now 5, because an_x.data is 5
Run Code Online (Sandbox Code Playgroud)
值得注意的是,返回引用会使表达式的结果为左值:
an_x.get1() = 5; // Compile-time error, because a float is not an lvalue.
an_x.get2() = 5; // Compiles, and sets an_x.data to 5.
Run Code Online (Sandbox Code Playgroud)
这是标准库容器使用的技术; vector<int>例如int &从非const operator[]重载返回,这就是some_vector[0] = 5;编译和工作的原因.