引用的用法1:
#include<iostream>
using namespace std;
int main()
{
int x = 10;
int y = 20;
cout << &x << endl;
cout << &y << endl;
int &rx = x;
cout << &x << endl;
cout << &rx << endl;
cout<<rx<<endl;
rx = y;
cout << &rx << endl;
cout << rx << endl;
while (1); //system("pause");
return 0;
}
运行结果如下:
引用的用法2:
#include<iostream>
using namespace std;
void funcr(int &num, int x)
{
cout << "in funcr,addr is:" << &num << endl; // 对比地址,等于原地址
num = x; // 会改变传入参数的值
}
// 不能写成void funcr(int num , int x),不正确的重载,导致不知道该调用谁
void func(int num, int x)
{
cout << "in func,addr is:" << &num << endl; // 对比地址,有所变化
num = x; // 只会在函数内改变拷贝变量的值,不会改变传入的参数值
}
int main()
{
int x = 100;
int &rx = x;
cout << "addr_x:" << &x << endl;
cout << "addr_rx:" << &rx << endl; // 变量地址和它的引用地址相同
//改变传入参数的值,不管代码中传的是变量本身还是引用
funcr(x, 177);
cout << "after funcr , x=" << x << endl;
//改变传入参数的值
funcr(rx, 211);
cout << "after funcr , rx=" << x << endl;
//不会改变传入参数的值,不管代码中传的是变量本身还是引用
func(rx, 233);
cout << "after func , rx=" << x << endl;
system("pause");
return 0;
}
运行结果如下: