共用方式為


this 指標

this 指標是只能在 classstructunion 類型的非靜態成員函式內存取的指標。 它會指向針對其呼叫成員函式的物件。 靜態成員函式沒有 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 指標會被直接使用,例如處理自引用資料結構時,其中需要當前對象的位址。

範例

// 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。 它可以是 constvolatile (或兩者)。 class-type 是 class 的名稱。

無法重新指派 this 指標。 成員函式宣告中使用的 constvolatile 限定詞會套用至該函式範圍中 this 指標指向的 class 執行個體,如下表所示:

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

以下表格詳細介紹了 constvolatile

this 修飾詞的語意

修飾詞 意義
const 無法變更成員資料;無法叫用非 const 的成員函式。
volatile 每次存取成員時,就會從記憶體載入成員資料,而且會停用某些最佳化。

const 物件傳遞至非 const 的成員函式會發生錯誤。

同樣地,將 volatile 物件傳遞至非 volatile 的成員函式也會發生錯誤。

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

注意

建構函式和解構函式無法宣告為 constvolatile。 不過,它們可以在 constvolatile 物件上叫用。

另請參閱

關鍵字