这是交换2个数字的代码,它工作正常。但是我对交换函数中x1和x2前面的“&”很好奇。在添加这两个代码之前,我的代码无法工作。 “&”的作用是什么?
#include<iostream>
using namespace std;
void swap(int &x1,int &x2){
int x = x1;
x1 = x2;
x2 = x;
}
int main(){
int n1 , n2;
cin >> n1 >> n2;
swap(n1,n2);
cout<<n1<<" "<<n2;
return 0;
}
在此功能:
void swap(int &x1,int &x2)
&
表示其对传入的参数的引用。更改这些变量将在调用站点上更改参数。
在此功能:
void swap(int x1,int x2)
复制参数。更改这些变量将not更改调用站点的参数。
即使没有功能,也是如此。例如
int a = 42;
int &b = a;
b = 5; // now a is also 5