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

VC++ 深度解析 C++ this 指標:解決參數遮蓋成員變數的關鍵

     編輯:VC 教學

前言

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 解析為參數,非成員。賦值操作無意義。

解決方案一:this->member 明確指定

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_。

this 指標本質

  • **型別**:ClassName* const (指向 const 的指標,不可修改指向)。
  • **隱含傳遞**:呼叫 pt.input(10,10) 實際傳遞 &pt 給隱含參數 this。
  • **成員存取轉換**:x = 0 → this->x = 0;func() → this->func()。
  • **靜態成員函數無 this**:因不屬於特定物件。

進階用法

1. 回傳 *this 實現鏈式呼叫

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);

2. 避免自我指派 (賦值運算子)

Point& operator=(const Point& rhs) {
    if (this == &rhs) return *this; // 偵測自我指派
    x = rhs.x; y = rhs.y;
    return *this;
}

3. 在建構函數中註冊 this 到管理器

class Manager;
class Object {
public:
    Object(Manager* m) { m->register(this); }
};

常見誤區

誤區正確觀念
this 是 referencethis 是 pointer (Class* const),C++ 無「this reference」。
建構函數可用 this 呼叫虛函數建構/解構期間虛函數機制失效,會調用當前類別版本 (非衍生類覆寫版)。
delete this 後可繼續用 thisdelete this 後物件生命結束,存取 this 為未定義行為。

總結

this 指標是「物件自我認知」的關鍵。參數遮蓋成員時,**this->member 是標準、明確、無效能損失的解法**。深入理解 this 的隱含傳遞、型別、生命週期限制,能寫出更安全的 C++ 程式碼 (如正確實作賦值運算子、啟用鏈式呼叫、避免建構期虛函數陷阱)。

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