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

要檢視有關 C++ 指標的更多詳細資訊,請檢視C++ 指標章節。

現在,讓我們透過指標傳遞值來呼叫 `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.
      * &a indicates pointer to a ie. address of variable a and 
      * &b indicates pointer to b ie. address of variable b.
   */
   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
廣告