C++ 解引用



在 C++ 中,解引用是指幫助訪問 指標 所指向的值的過程。其中指標儲存該特定值的記憶體地址。要訪問或修改儲存在該地址處的值,可以使用由 (*) 表示的解引用運算子。

解引用以讀取值

以下是訪問儲存在指標指向的地址處的值的語法:

Type value = *pointer; 
// Gets the value at the address pointed to by the pointer

解引用以修改值

解引用運算子的語法,用於修改指標指向的地址處的值:

*pointer = newValue; 
// Sets the value at the address pointed to by the pointer

C++ 解引用的示例

以下是一個說明 C++ 中解引用的簡單示例:

#include <iostream>
using namespace std;

int main() {
   int number = 42;        // A normal integer variable
   int* ptr = &number;     // Pointer that holds the address of 'number'

   // Dereferencing to read the value
   cout << "Original Value: " << *ptr << endl;  

   // Dereferencing to modify the value
   *ptr = 100;  
   cout << "Modified Value: " << number << endl;  
   return 0;
}

輸出

Original Value: 42
Modified Value: 100

解釋

  • 首先,我們聲明瞭一個名為 number 的整數變數,並將其初始化為值 42。
  • 聲明瞭一個數據型別為整數的指標 ptr。使用取地址運算子 & 將指標分配給 number 的地址,這意味著 ptr 將指向 number 的記憶體地址位置。
  • 現在,我們使用解引用運算子 * 來訪問儲存在 ptr 指向的地址處的值。
  • *ptr = 100; 此行再次使用解引用運算子,但這次用於賦值新值。

引用與解引用

引用 解引用
定義 引用 是另一個變數的變數,它允許您訪問或修改原始變數,而無需直接使用其名稱。 解引用是訪問指標儲存的記憶體地址處儲存的值的過程。
符號 & (用於宣告) * (用於表示式)
語法 dataType& referenceName = existingVariable; dataType pointerVariable = *pointerName;

顯示引用和解引用的示例

以下是一個在程式碼中同時說明引用和解引用的示例。

#include <iostream>
using namespace std;

int main() {
   int number = 42;

   // Pointer holding the address of 'number'
   int* ptr = &number;        

   // Reference to 'number'
   int& ref = number;         

   // Using pointer to read the value (dereferencing ptr)
   cout << "Original Value (pointer): " << *ptr << endl; 

   // Using reference to read the value
   cout << "Original Value (reference): " << ref << endl;  

   // Modifying the value through the pointer (dereferencing ptr)
   *ptr = 100;  
   cout << "Modified Value (pointer): " << number << endl;  
   cout << "Modified Value (reference): " << ref << endl;

   // Modifying the value through the reference
   ref = 200;  
   cout << "Modified Value (reference): " << number << endl;  
   cout << "Modified Value (pointer): " << *ptr << endl; 

   return 0;
}

輸出

Original Value (pointer): 42
Original Value (reference): 42
Modified Value (pointer): 100
Modified Value (reference): 100
Modified Value (reference): 200
Modified Value (pointer): 200
廣告