问题描述
关于为什么有必要从函数返回引用的问题.
Question about why is it necessary at all to return a reference from a function.
以下代码的行为完全相同,如果我们将第 9 行和第 16 行中的 int&
替换为 int
.
Following code behaves exactly the same, if we replace int&
with int
in line9 and line16.
在我的示例代码中是否正确,返回引用与值无关紧要?在什么样的例子中它会开始重要?
Is it true in my example code, returning reference vs value doesnt matter? In what kind of example it will start to matter?
在我看来,我们不能返回函数的局部变量的引用,因为局部变量将超出调用者的范围.因此,只返回调用者可以看到的变量的引用(在范围内)才有意义,但是如果函数的调用者可以看到该变量,那么它就不需要返回(?)(或者这是返回是为了保持代码整洁?)
In my mind, we cant return the reference of a local variable of the function, since the local variable will be out of scope for the caller. Therefore, it only make sense to return a reference of a variable that the caller can see (in scope), but if the caller of the function can see the variable, then it doesnt need to be returned(?) (or is this returning done for the sake of keeping the code neat and tidy?)
相关链接:返回引用是个好主意吗?
#include <iostream>
using namespace std;
class myClass{
private:
int val;
public:
myClass(int);
int& GetVal();
};
myClass::myClass(int x){
val = x;
}
int& myClass::GetVal(){
return val;
}
int main()
{
myClass myObj(666);
cout << myObj.GetVal() << endl;
system("pause");
return 0;
}
推荐答案
不同的是,当你返回一个引用时,你可以赋值给GetVal()
的结果:
The difference is that, when you return a reference, you can assign to the result of GetVal()
:
myObj.GetVal() = 42;
你也可以保留返回的引用,以后用它来修改myObj.val
.
You can also keep the returned reference around, and use it to modify myObj.val
later.
如果 GetVal()
要按值返回 val
,这一切都不可能.
If GetVal()
were to return val
by value, none of this would be possible.
这是否是可取的,或者是否确实是好的设计,完全是一个不同的问题.
Whether any of this is desirable, or indeed good design, is a different question altogether.
请注意,您的示例与 链接中的代码非常不同问题 -- 该代码返回无效引用,这无疑是个坏主意.
Note that your example is very different to the code in the linked question -- that code returns an invalid reference and is unequivocally a bad idea.
这篇关于返回引用与返回值 C++ 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!