位置:首頁 > 高級語言 > C++教學 > C++通過引用傳遞參數

C++通過引用傳遞參數

我們已經討論了如何使用指針引用的概念實現調用。下麵是調用引用一個例子,這使得使用C++參考:

#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.*/
   swap(a, b);
 
   cout << "After swap, value of a :" << a << endl;
   cout << "After swap, value of b :" << b << endl;
 
   return 0;
}
 
// 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;
}

當上述代碼被編譯和執行時,它產生了以下結果:

Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100