- C++ 基礎
- C++ 首頁
- C++ 概述
- C++ 環境設定
- C++ 基本語法
- C++ 註釋
- C++ Hello World
- C++ 省略名稱空間
- C++ 常量/字面量
- C++ 關鍵字
- C++ 識別符號
- C++ 資料型別
- C++ 數值資料型別
- C++ 字元資料型別
- C++ 布林資料型別
- C++ 變數型別
- C++ 變數作用域
- C++ 多個變數
- C++ 基本輸入/輸出
- C++ 修飾符型別
- C++ 儲存類
- C++ 運算子
- C++ 數字
- C++ 列舉
- C++ 引用
- C++ 日期和時間
- C++ 控制語句
- C++ 決策制定
- C++ if 語句
- C++ if else 語句
- C++ 巢狀 if 語句
- C++ switch 語句
- C++ 巢狀 switch 語句
- C++ 迴圈型別
- C++ while 迴圈
- C++ for 迴圈
- C++ do while 迴圈
- C++ foreach 迴圈
- C++ 巢狀迴圈
- C++ break 語句
- C++ continue 語句
- C++ goto 語句
- C++ 建構函式
- C++ 建構函式和解構函式
- C++ 複製建構函式
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
廣告