C++ 把引用作为参数


我们已经讨论了如何使用指针来实现引用调用函数。下面的实例使用了引用来实现引用调用函数。

  1. #include <iostream>
  2. using namespace std;
  3. // 函数声明
  4. void swap(int& x, int& y);
  5. int main ()
  6. {
  7. // 局部变量声明
  8. int a = 100;
  9. int b = 200;
  10. cout << "交换前,a 的值:" << a << endl;
  11. cout << "交换前,b 的值:" << b << endl;
  12. /* 调用函数来交换值 */
  13. swap(a, b);
  14. cout << "交换后,a 的值:" << a << endl;
  15. cout << "交换前,b 的值:" << b << endl;
  16. return 0;
  17. }
  18. // 函数定义
  19. void swap(int& x, int& y)
  20. {
  21. int temp;
  22. temp = x; /* 保存地址 x 的值 */
  23. x = y; /* 把 y 赋值给 x */
  24. y = temp; /* 把 x 赋值给 y */
  25. return;
  26. }

当上面的代码被编译和执行时,它会产生下列结果:

  1. 交换前,a 的值: 100
  2. 交换前,b 的值: 200
  3. 交换后,a 的值: 200
  4. 交换后,b 的值: 100