this 指標是 C++ 非靜態成員函數的隱含參數,指向呼叫物件本身。本文透過經典「參數名稱與成員變數同名導致賦值失效」案例,示範 this->member 明確存取成員的正確用法,並解析 this 在物件模型中的角色。
class Point {
public:
int x, y;
Point(int a, int b) { x = a; y = b; }
void input(int x, int y) { // 參數 x, y 遮蓋成員 x, y
x = x; // 參數賦值給參數,成員未被修改!
y = y;
}
void output() { cout << x << endl << y << endl; }
};
int main() {
Point pt(5, 5);
pt.input(10, 10);
pt.output(); // 輸出 5, 5 (非預期 10, 10)
}
原因:函數內 x、y 解析為參數,非成員。賦值操作無意義。
void input(int x, int y) {
this->x = x; // this->x 為成員,右邊 x 為參數
this->y = y;
}
編譯執行後,pt.input(10,10) 正確修改成員,output() 輸出 10, 10。
void input(int newX, int newY) {
x = newX; y = newY; // 無遮蓋,直接存取成員
}
常見命名慣例:aX, nX, _x, x_。
ClassName* const (指向 const 的指標,不可修改指向)。pt.input(10,10) 實際傳遞 &pt 給隱含參數 this。x = 0 → this->x = 0;func() → this->func()。class Point {
public:
int x, y;
Point& setX(int v) { x = v; return *this; }
Point& setY(int v) { y = v; return *this; }
};
// 使用
pt.setX(1).setY(2).setX(3);
Point& operator=(const Point& rhs) {
if (this == &rhs) return *this; // 偵測自我指派
x = rhs.x; y = rhs.y;
return *this;
}
class Manager;
class Object {
public:
Object(Manager* m) { m->register(this); }
};
| 誤區 | 正確觀念 |
|---|---|
| this 是 reference | this 是 pointer (Class* const),C++ 無「this reference」。 |
| 建構函數可用 this 呼叫虛函數 | 建構/解構期間虛函數機制失效,會調用當前類別版本 (非衍生類覆寫版)。 |
| delete this 後可繼續用 this | delete this 後物件生命結束,存取 this 為未定義行為。 |
this 指標是「物件自我認知」的關鍵。參數遮蓋成員時,**this->member 是標準、明確、無效能損失的解法**。深入理解 this 的隱含傳遞、型別、生命週期限制,能寫出更安全的 C++ 程式碼 (如正確實作賦值運算子、啟用鏈式呼叫、避免建構期虛函數陷阱)。