跳轉到內容

C++ 程式設計/類/this

來自華夏公益教科書,自由的教科書

this 指標

[編輯 | 編輯原始碼]

this 關鍵字充當指向被引用類的指標。this 指標的行為與其他指標相同,儘管您無法更改指標本身。閱讀關於 指標和引用 的部分以瞭解有關一般指標的更多資訊。

this 指標只能在類的、聯合的或結構的非靜態成員函式中訪問,在靜態成員函式中不可用。無需為this 指標編寫程式碼,因為編譯器會隱式地執行此操作。在使用偵錯程式時,您可以在程式單步執行非靜態類函式時在某些變數列表中看到this 指標。

在以下示例中,編譯器在非靜態成員函式 int getData() 中插入了隱式引數this。此外,啟動呼叫的程式碼傳遞了一個隱式引數(由編譯器提供)。

class Foo
{
private:
    int iX;
public:
    Foo(){ iX = 5; };

    int getData() 
    {   
        return this->iX;  // this is provided by the compiler at compile time
    }
};

int main()
{
    Foo Example;
    int iTemp;

    iTemp = Example.getData(&Example);  // compiler adds the &Example reference at compile time

    return 0;
}

在某些情況下,程式設計師應該瞭解並使用this 指標。在過載賦值運算子時,應該使用this 指標來防止災難。例如,在上面的程式碼中新增一個賦值運算子。

class Foo
{
private:
    int iX;
public:
    Foo() { iX = 5; };

    int getData()          
    {                            
        return iX;  
    }

    Foo& operator=(const Foo &RHS);
};

Foo& Foo::operator=(const Foo &RHS)
{
    if(this != &RHS)
    {    // the if this test prevents an object from copying to itself (ie. RHS = RHS;)
        this->iX = RHS.iX;     // this is suitable for this class, but can be more complex when
                               // copying an object in a different much larger class
    }

    return (*this);            // returning an object allows chaining, like a = b = c; statements
}

無論您對this 瞭解多少,它在實現任何類中都至關重要。

華夏公益教科書