我知道以下关于引用
例如。 int &ref=x;
然后 ref 和 x 是内存中相同位置的名称。
与指针不同,内存不是为引用分配的。
我正在使用我成功编写的引用在 C++ 中编写一个简单的交换程序。
然后我决定尝试当返回引用的函数是表达式的 LHS 时会发生什么,现在我无法预测下面代码的输出。
#include<iostream.h>
int & swap(int &,int &); //function returns reference
void main()
{
int x=10,y=20;
int &ref1=x,&ref2=y;
swap(ref1,ref2)=x; //what happens here?
cout<<x<<y;
}
int & swap(int &ref1,int &ref2)
{
int temp;
temp=ref1; //swap
ref1=ref2; //code
ref2=temp; //here
return ref2; //tried out this(has nothing to do with swapping)
}
O/P 20 20
最佳答案
有两种可能的结果:
- “2010”
- “2020”
这取决于右边的x
是在调用左边的swap
之前还是之后读取的。
标准不禁止发生哪种情况,只是它们不交错。
关于c++ - 当函数返回引用写在 LHS 上时无法预测输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25980494/