首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ this 指針深度解析:自我賦值檢查、鏈式調用、const 正確性

     編輯:程式設計綜合問答

經典代碼片段

void A::copy(A& aa) {
    if (this == &aa) return; // 自我賦值檢查
    *this = aa;              // 執行賦值
}

this 本質

  • 類非靜態成員函數的**隱含參數**,類型為 A* const(指針常量,不可修改指向)。
  • 指向**調用該函數的對象實例**地址。
  • 在構造函數/析構函數中已可用,但虛函數調用行為特殊(調用當前類版本)。

三大核心用途

用途代碼模式說明
區分同名參數/字段this->member = member;構造器/Setter 常見
自我賦值檢查if (this == &other) return *this;賦值運算符/拷貝函數必加
鏈式調用返回return *this;Setter、運算符重載、Builder 模式

const 正確性

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(); 調用。

進階:CRTP (Curiously Recurring Template Pattern)

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++ 面向對象編程的基石技能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved