
举例:
#include<iostream>
using namespace std;
int main()
{
int n = 7;
int & r = n;
r = 4;
cout << r << endl;
cout << n << endl;
n = 5;
cout << r << endl;
}
输出
4
4
5
注意事项:

举例:

#include<iostream>
using namespace std;
void swap(int & a, int & b)//引用,不需要取地址
{
int tmp;
tmp = a;
a = b;
b = tmp;
}
int main()
{
int n1 = 2, n2 = 3;
swap(n1,n2);
cout << n1 <<" "<< n2;
}
#include<iostream>
using namespace std;
int n = 4;
int & SetValue() { return n; } //返回值为一个整型的引用,引用了n
int main()
{
SetValue() = 40;//对函数调用的结果进行赋值,等价于对n进行复制
cout << n << endl; //n=40
return 0;
}
定义引用时,在前面加const关键字
int n;
const int & r = n; // r的类型为const int &
特点:不能通过常引用修改其引用的内容


原文:https://www.cnblogs.com/rookieveteran/p/13803317.html