基本概念
this 是類成員函數中的隱含指針,指向調用該函數的對象。只能在非靜態成員函數中使用。
等價調用示例
void Date::setMonth(int mn) {
month = mn; // 隱式使用 this
this->month = mn; // 顯式使用 this
(*this).month = mn; // 解引用後訪問
}
核心特性
- 只能在成員函數中使用:全局函數、靜態成員函數無
this。
- 隱含參數:編譯器將成員函數第一個參數作為
T* const register this 傳遞。如 int A::func(int p) 實際為 int func(A* const register this, int p)。
- 生命週期:函數調用前構造,調用後銷毀,與普通參數一致。
- 調用機制:
a.func(10) 編譯為 A::func(&a, 10)。編譯器常優化通過寄存器(如 VC 用 ecx)傳遞 this。
- 存儲位置:視編譯器而定,可能在棧、寄存器甚至全局區。
常見問題解答
| 問題 | 回答 |
| this 何時創建? | 成員函數開始執行前構造,結束後清除。 |
| this 存放在哪? | 編譯器決定:棧、寄存器或全局區。 |
| 如何傳遞給函數? | 作為第一個隱含參數(通常通過寄存器)。 |
| 如何訪問成員? | 同結構體指針訪問成員,this->member 即 (*this).member。 |
| 能否在函數外使用 this? | 不能。this 僅在成員函數作用域內存在。 |
| 類是否有函數表? | 普通函數無表,僅虛函數有 vtable。編譯器若能確定調用目標,會直接調用而不經 vtable。 |
模擬實現 this 調用
系統回調函數(如線程入口)常需模擬成員函數調用:
class A {
int n;
public:
static void run(void* pThis) { // 靜態函數作為回調入口
A* this_ = (A*)pThis; // 手動轉換 this
this_->process(); // 調用真實成員函數
}
void process() {}
};
int main() {
A a;
_beginthread(A::run, 0, &a); // 傳遞 this 指針
}
這本質上是 C 風格的「手動 this 傳遞」:
typedef struct { int age; int no; } Student;
void initStudent(Student* pstudent); // pstudent 即相當於 this
void addScore(Student* pstudent, int score);
關於 const 與 this
const 成員函數中 this 類型為 const T* const,不可修改成員。
mutable 成員可在 const 函數中修改。
總結
this 是 C++ 實現面向對象的核心機制,本質是編譯器自動傳遞的隱含指針參數。理解其本質有助於掌握成員函數調用、虛函數分發、回調綁定等底層原理。
- 上一篇文章: ZOJ 3632 Watermelon Full of Water — 線段樹區間更新 + DP 優化
- 下一篇文章: HDU 4662 MU Puzzle — 字符串變換規律與數學解法
Copyright ©
程式碼之家 All Rights Reserved