当尝试使用引用交换它们时,两个变量最终具有相同的值
Both variables end up having same value when trying to swap them using references
我正在尝试交换两个变量的内容。我用指针做得很好。但是尝试使用引用来实现它是行不通的。
#include <iostream>
//Implementing a reference based swap
void RefSwap(int& x, int& y)
{
int extra;
extra = x; //automatically de-referenced
x = y;
y = extra;
}
int main()
{
int a = 3, b = 10;
int& ref_a = a, ref_b = b; //refs don't actually exist in memory, they act like aliases
RefSwap(ref_a, ref_b);
std::cout << a << " " << b << std::endl;
}
我的输出:
10 10
预期输出:
10 3
使用 VS 社区 2022
int& ref_a = a, ref_b = b;
这是
int& ref_a = a;
int ref_b = b;
不是:
int& ref_a = a;
int& ref_b = b;
变化:
int& ref_a = a, ref_b = b;
收件人:
int& ref_a = a;
int& ref_b = b;
将产生正确的结果。
我正在尝试交换两个变量的内容。我用指针做得很好。但是尝试使用引用来实现它是行不通的。
#include <iostream>
//Implementing a reference based swap
void RefSwap(int& x, int& y)
{
int extra;
extra = x; //automatically de-referenced
x = y;
y = extra;
}
int main()
{
int a = 3, b = 10;
int& ref_a = a, ref_b = b; //refs don't actually exist in memory, they act like aliases
RefSwap(ref_a, ref_b);
std::cout << a << " " << b << std::endl;
}
我的输出:
10 10
预期输出:
10 3
使用 VS 社区 2022
int& ref_a = a, ref_b = b;
这是
int& ref_a = a;
int ref_b = b;
不是:
int& ref_a = a;
int& ref_b = b;
变化:
int& ref_a = a, ref_b = b;
收件人:
int& ref_a = a;
int& ref_b = b;
将产生正确的结果。