this 是 C++ 關鍵字,同時是一個 const 指標,指向「正在呼叫成員函數的那個物件」(當前物件)。它隱含於每個非靜態成員函數中,型別為 ClassName* const(指標本身不可修改,指向內容可讀寫)。
class Student {
public:
void setName(const char* name) { this->name = name; } // 區分參數 name 與成員 name
void setAge(int age) { this->age = age; }
void show() const { cout << this->name << " " << this->age << endl; }
private:
const char* name;
int age;
};
若不加 this->,name = name 將變成參數自我指派,成員變數保持未初始化狀態。
編譯器將非靜態成員函數轉換為:
// 原始碼
void Student::setAge(int age) { this->age = age; }
// 編譯器視角(偽碼)
void Student_setAge(Student* const this, int age) {
this->age = age;
}
this 是成員函數的第一個隱含參數。stu.setAge(18) 實際傳遞 &stu 作為 this。this 只能在成員函數內部使用,且物件建立後才有值。class Demo {
public:
void printThis() const { cout << "this = " << this << endl; }
};
int main() {
Demo a, b;
a.printThis(); // 輸出 a 的位址
cout << "&a = " << &a << endl; // 相同
b.printThis(); // 輸出 b 的位址
cout << "&b = " << &b << endl; // 相同
return 0;
}
this = &other;、++this 皆非法。this 已可用,但成員尚未完全初始化時需謹慎使用。class Calculator {
int value = 0;
public:
Calculator& add(int n) { value += n; return *this; }
Calculator& mul(int n) { value *= n; return *this; }
int get() const { return value; }
};
int main() {
Calculator c;
cout << c.add(10).mul(2).add(5).get(); // (10*2)+5 = 25
return 0;
}
回傳 *this(物件引用)實現鏈式介面,廣泛用於串流(cout << a << b)、建構者模式等。
delete this;:極度危險,除非極度確定物件以 new 配置且後續不再使用(如 COM 參考計數),否則嚴禁。this:編譯錯誤,靜態函數無隱含參數。this 是引用:它是指標,存取成員需用 -> 或 *this.。this 是成員函數與其所屬物件的橋樑,本質為隱含 const 指標參數。掌握其「解決名稱遮蔽、實現鏈式呼叫、傳遞物件位址」三大核心用法,並遵守三大鐵律,即能駕馭 C++ 物件模型的核心機制。