C++ 引用調(diào)用

C++ 函數(shù) C++ 函數(shù)

向函數(shù)傳遞參數(shù)的引用調(diào)用方法,把引用的地址復(fù)制給形式參數(shù)。在函數(shù)內(nèi),該引用用于訪問調(diào)用中要用到的實際參數(shù)。這意味著,修改形式參數(shù)會影響實際參數(shù)。

按引用傳遞值,參數(shù)引用被傳遞給函數(shù),就像傳遞其他值給函數(shù)一樣。因此相應(yīng)地,在下面的函數(shù) swap() 中,您需要聲明函數(shù)參數(shù)為引用類型,該函數(shù)用于交換參數(shù)所指向的兩個整數(shù)變量的值。

// 函數(shù)定義
void swap(int &x, int &y)
{
   int temp;
   temp = x; /* 保存地址 x 的值 */
   x = y;    /* 把 y 賦值給 x */
   y = temp; /* 把 x 賦值給 y  */
  
   return;
}

現(xiàn)在,讓我們通過引用傳值來調(diào)用函數(shù) swap()

#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;
}

當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:

交換前,a 的值: 100
交換前,b 的值: 200
交換后,a 的值: 200
交換后,b 的值: 100

C++ 函數(shù) C++ 函數(shù)