this指標

this指標是只能在、 structunion 類型的非靜態成員函式中存取的class指標。 它會指向針對其呼叫成員函式的物件。 靜態成員函式沒有 this 指標。

語法

this
this->member-identifier

備註

物件的 this 指標不是物件本身的一部分。 它不是 對象上語句結果的一 sizeof 部分。 針對物件呼叫非靜態成員函式時,編譯程式會將對象的位址傳遞至函式做為隱藏自變數。 例如,下列函式呼叫:

myDate.setMonth( 3 );

可以解譯為:

setMonth( &myDate, 3 );

物件位址可從成員函式內做為 this 指標使用。 大部分 this 的指標用法都是隱含的。 雖然不必要,但在參考 的成員class時使用明確this,但這是合法的。 例如:

void Date::setMonth( int mn )
{
   month = mn;            // These three statements
   this->month = mn;      // are equivalent
   (*this).month = mn;
}

*this 運算式通常用來從成員函式傳回目前物件:

return *this;

指標 this 也可用來防範自我參考:

if (&Object != this) {
// do not execute in cases of self-reference

注意

this因為指標不可修改,this因此不允許指派指標。 舊版 C++ 的實作允許指派給 this

有時候, this 會直接使用指標,例如,用來操作自我參考數據 struct擷取,其中需要目前對象的位址。

範例

// this_pointer.cpp
// compile with: /EHsc

#include <iostream>
#include <string.h>

using namespace std;

class Buf
{
public:
    Buf( char* szBuffer, size_t sizeOfBuffer );
    Buf& operator=( const Buf & );
    void Display() { cout << buffer << endl; }

private:
    char*   buffer;
    size_t  sizeOfBuffer;
};

Buf::Buf( char* szBuffer, size_t sizeOfBuffer )
{
    sizeOfBuffer++; // account for a NULL terminator

    buffer = new char[ sizeOfBuffer ];
    if (buffer)
    {
        strcpy_s( buffer, sizeOfBuffer, szBuffer );
        sizeOfBuffer = sizeOfBuffer;
    }
}

Buf& Buf::operator=( const Buf &otherbuf )
{
    if( &otherbuf != this )
    {
        if (buffer)
            delete [] buffer;

        sizeOfBuffer =  strlen( otherbuf.buffer ) + 1;
        buffer = new char[sizeOfBuffer];
        strcpy_s( buffer, sizeOfBuffer, otherbuf.buffer );
    }
    return *this;
}

int main()
{
    Buf myBuf( "my buffer", 10 );
    Buf yourBuf( "your buffer", 12 );

    // Display 'my buffer'
    myBuf.Display();

    // assignment operator
    myBuf = yourBuf;

    // Display 'your buffer'
    myBuf.Display();
}
my buffer
your buffer

指標的類型this

指標 this 的類型會根據函式宣告是否包含 const 和/或 volatile 關鍵詞而變更。 下列語法描述成員函式中的 類型 this

[cv-qualifier-list] class-type* const this

成員函式的宣告子會 cv-qualifier-list決定 。 它可以是 constvolatile (或兩者)。 class-type 是的名稱 class。

this指標無法重新指派。 const成員函式宣告中使用的 或 volatile 限定符會套用至class該函式範圍中指標指向的實例this,如下表所示:

成員函式宣告 具名的 this 指標 class 類型 myClass
void Func() myClass *
void Func() const const myClass *
void Func() volatile volatile myClass *
void Func() const volatile const volatile myClass *

下表說明和 ''volatile' 的詳細資訊const

修飾詞的 this 語意

修飾詞 意義
const 無法變更成員數據;無法叫用不是 const的成員函式。
volatile 每次存取成員數據時,都會從記憶體載入;會停用特定優化。

將對象傳遞 const 至不是 const的成員函式時發生錯誤。

同樣地,將 對象傳遞 volatile 至不是 volatile的成員函式也是錯誤。

宣告為 const 的成員函式無法變更成員數據。 在 const 函式中 this ,指標是 物件的指標 const

注意

Constructors 和 destructors 無法宣告為 constvolatile。 不過,可以在或 volatile 物件上const叫用它們。

另請參閱

關鍵字