首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 基礎

C++ this 指標深度解析

     編輯:C++ 基礎

this 是什麼?

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 將變成參數自我指派,成員變數保持未初始化狀態。

this 的本質:隱含函數參數

編譯器將非靜態成員函數轉換為:

// 原始碼
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 只能在成員函數內部使用,且物件建立後才有值。

證明 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;
}

三大鐵律

  1. const 指標:this = &other;、++this 皆非法。
  2. 僅限成員函數內部:全域函數、靜態成員函數不可用。
  3. 物件建立後才有效:建構函數執行期間 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++ 物件模型的核心機制。

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