C++引用傳遞函式呼叫



將引數傳遞給函式的引用傳遞方法將引數的引用複製到形式引數中。在函式內部,引用用於訪問呼叫中使用的實際引數。這意味著對引數所做的更改會影響傳遞的引數。

要透過引用傳遞值,將引數引用傳遞給函式,就像傳遞任何其他值一樣。因此,您需要像以下函式swap()一樣將函式引數宣告為引用型別,該函式交換其引數指向的兩個整型變數的值。

// function definition to swap the values.
void swap(int &x, int &y) {
   int temp;
   temp = x; /* save the value at address x */
   x = y;    /* put y into x */
   y = temp; /* put x into y */
  
   return;
}

現在,讓我們透過引用傳遞值來呼叫函式swap(),如下例所示:

#include <iostream>
using namespace std;

// function declaration
void swap(int &x, int &y);

int main () {
   // local variable declaration:
   int a = 100;
   int b = 200;
 
   cout << "Before swap, value of a :" << a << endl;
   cout << "Before swap, value of b :" << b << endl;

   /* calling a function to swap the values using variable reference.*/
   swap(a, b);

   cout << "After swap, value of a :" << a << endl;
   cout << "After swap, value of b :" << b << endl;
 
   return 0;
}

當以上程式碼放在一個檔案中,編譯並執行時,會產生以下結果:

Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
cpp_functions.htm
廣告