返回参考值和返回值C ++之间的差异 [英] Difference between returning reference vs returning value C++

查看:149
本文介绍了返回参考值和返回值C ++之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关为什么必须从函数返回引用的问题。



以下代码的行为完全相同,如果我们替换



在我的示例中是真的。

代码,返回引用对价值没有关系吗?在什么样的例子中它会开始重要?



在我看来,我们无法返回函数的局部变量的引用,因为局部变量将超出调用者的范围。因此,它只有返回一个变量的引用,调用者可以看到(在范围内),但是如果函数的调用者可以看到变量,那么它不需要返回(?)(或者是返回)



相关链接:

  #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()的结果:

  myObj.GetVal()= 42; 

您还可以保留返回的引用,并使用它修改 myObj



如果 GetVal()返回<$ c $



这些都是可取的,或者好的设计,是不同的



请注意,您的示例与链接问题 - 代码返回一个无效的引用,明确是一个坏主意。


Question about why is it necessary at all to return a reference from a function.

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?)

Related link: Is returning a reference ever a good idea?

#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;
}

解决方案

The difference is that, when you return a reference, you can assign to the result of GetVal():

myObj.GetVal() = 42;

You can also keep the returned reference around, and use it to modify myObj.val later.

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 ++之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆