代码清单4.1 对比引用与赋值的差异
#include <iostream>using namespace std;int main(){int i;int &r = i;i = 5;cout << "Value of i : " << i << endl;cout << "Value of i reference : " << r << endl;cout << "Addr of i: " << &i << endl;cout << "Addr of r: " << &r << endl;int x;int y = x;x = 6;cout << "Value of x : " << x << endl;cout << "Value of y : " << y << endl;cout << "Addr of x: " << &x << endl;cout << "Addr of y: " << &y << endl;return 0;}
输出结果为:
Value of i : 5 Value of i reference : 5 Addr of i: 0x7fff5decae04 Addr of r: 0x7fff5decae04 Value of x : 6 Value of y : 0 Addr of x: 0x7fff5decae08 Addr of y: 0x7fff5decae0c
可见引用的地址与所指向的对象地址是相同的。可以理解为是被指向对象的完美复制体。这一点与指针也是有明显的区别。引用更像是一个别名。
代码清单 4.2 用引用来代替指针传递参数
#include <iostream>using namespace std;void swap(int &x, int &y);int main(){int a = 100;int b = 200;cout << "交换前,a 的值:" << a << endl;cout << "交换前,b 的值:" << b << endl;swap(a, b);cout << "交换后,a 的值:" << a << endl;cout << "交换后,b 的值:" << b << endl;return 0;}void swap(int &x, int &y){int temp;temp = x; /* 保存地址 x 的值 */x = y; /* 把 y 赋值给 x */y = temp; /* 把 x 赋值给 y */return;}
代码清单 4.3 使用引用来返回参数
#include <iostream>
using namespace std;
double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0};
double &setValues(int i)
{
return vals[i];
}
int main()
{
cout << "改变前的值" << endl;
for (int i = 0; i < 5; i++)
{
cout << "vals[" << i << "] = ";
cout << vals[i] << endl;
}
setValues(1) = 20.23; // 相当于返回元素[1]的引用,然后修改此引用的值
cout << "改变后的值" << endl;
for (int i = 0; i < 5; i++)
{
cout << "vals[" << i << "] = ";
cout << vals[i] << endl;
}
return 0;
}
代码清单 4.4 使用引用来返回类对象
C++中 如果返回值是一个类的对象,那么会创建一个临时的类对象,返回以后销毁。这样明显增加了不必要的开销。可以将返回设置为对象的引用来规避。
但这样会修改原始的值
在不影响运算结果的话,优先使用引用返回。
