void A::copy(A& aa) {
if (this == &aa) return; // 自我賦值檢查
*this = aa; // 執行賦值
}
A* const(指針常量,不可修改指向)。| 用途 | 代碼模式 | 說明 |
|---|---|---|
| 區分同名參數/字段 | this->member = member; | 構造器/Setter 常見 |
| 自我賦值檢查 | if (this == &other) return *this; | 賦值運算符/拷貝函數必加 |
| 鏈式調用返回 | return *this; | Setter、運算符重載、Builder 模式 |
class A {
int val;
public:
A& setVal(int v) { val = v; return *this; } // 非 const,可修改
int getVal() const { return val; } // const 成員函數,this 類型為 const A*
const A& getConstRef() const { return *this; } // 返回 const 引用,防修改
};
const 成員函數承諾不修改對象狀態,編譯器強制檢查,支持 const A obj; obj.getVal(); 調用。
template
class Base {
public:
Derived& derived() { return static_cast(*this); }
const Derived& derived() const { return static_cast(*this); }
};
class Child : public Base {
// 可調用 Base 返回 Child&,實現靜態多態鏈式調用
};
*this 時忘記引用返回類型 (A&),導致拷貝切片。this 可修改(如 this = nullptr;),編譯錯誤。理解 this 作為隱含參數的本質、const 約束、鏈式調用模式,是 C++ 面向對象編程的基石技能。