C++引用:
在C++语言中,我们用 数据类型名& 变量名 = 某个变量 的方式来定义一个引用。
例如:
#include <iostream>
using namespace std;
int main()
{
int n = 5;
int s = 6;
int & r = s;//定义引用r,r的类型为 int&
r = n;//只是赋值操作,不会改变引用r引用的变量
cout<<r<<endl;//输出5
cout<<s;//输出5,s的值随之改变
}
某个变量的引用等价于这个变量,相当于这个变量的另一个名字。
定义引用时就要将其初始化,一个引用初始化后就不能引用其他的变量。
在函数参数中使用引用时,可以直接传递变量:
#include<iostream>
using namespace std;
void swap(int& a,int&b){
int tmp = a;
a = b;
b = tmp;
}
int main()
{
int a = 3;
int b = 5;
//如何交换a,b?
cout<<a<<" "<<b<<endl;//输出 3 5,换行
swap(a,b);
cout<<a<<" "<<b<<endl;//输出5,3,换行
return 0;
}
返回值为 类型名& 类型的函数,可以通过引用来改变返回值:
#include <iostream>
using namespace std;
int n = 5;
int& getElem(){
return n;
}
int main()
{
getElem() = 10;
cout<<n<<endl;//输出10
}