C++ 中通过引用传递参数
我们已经讨论了如何使用指针实现通过引用调用的概念。这里是另一个使用 C++ 引用的通过引用调用的示例 -
#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; /* calling a function to swap the values.*/ 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; }
当编译并执行上述代码时,它会产生以下结果 -
交换之前,a 的值:100 交换之前, b 的值:200 交换后,a 的值:200 交换后,b的值:100