C++ 把引用作為參數(shù)
我們已經(jīng)討論了如何使用指針來實現(xiàn)引用調(diào)用函數(shù)。下面的實例使用了引用來實現(xiàn)引用調(diào)用函數(shù)。
#include <iostream> using namespace std; // 函數(shù)聲明 void swap(int& x, int& y); int main () { // 局部變量聲明 int a = 100; int b = 200; cout << "交換前,a 的值:" << a << endl; cout << "交換前,b 的值:" << b << endl; /* 調(diào)用函數(shù)來交換值 */ swap(a, b); cout << "交換后,a 的值:" << a << endl; cout << "交換前,b 的值:" << b << endl; return 0; } // 函數(shù)定義 void swap(int& x, int& y) { int temp; temp = x; /* 保存地址 x 的值 */ x = y; /* 把 y 賦值給 x */ y = temp; /* 把 x 賦值給 y */ return; }
當上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:
交換前,a 的值: 100 交換前,b 的值: 200 交換后,a 的值: 200 交換后,b 的值: 100
更多建議: