在C++中,this是一個隱含指針,指向調用成員函數的當前對象。它的關鍵特性:
this = &other 編譯錯誤)*this修改class Student {
string name;
public:
void setName(string name) {
this->name = name; // this->name 為成員,name 為參數
}
};
class Builder {
int value;
public:
Builder& add(int v) { value += v; return *this; }
Builder& mul(int v) { value *= v; return *this; }
};
// 用法:builder.add(2).mul(3).add(5);
Object& operator=(const Object& other) {
if (this != &other) { /* 深拷貝 */ }
return *this; // 返回引用支援連續賦值
}
❌ this = nullptr; 編譯錯誤
✅ *this = other; 調用賦值運算符,合法修改對象內容
掌握this指針,是寫出高效、安全C++代碼的關鍵基石。