共用方式為


this 指標

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

this 
this->member-identifier

備註

物件的 this 指標不屬於物件本身,因此不會在物件上 sizeof 陳述式的結果中反映出來。 不過,呼叫物件的非靜態成員函式時,編譯器會將物件的位址當做隱藏的引數傳遞至函式。 例如,下列函式呼叫:

myDate.setMonth( 3 );

可以用這種方式解譯:

setMonth( &myDate, 3 );

物件的位址可在成員函式內做為 this 指標使用。 this 的用法大多是隱含的。 在參考類別的成員時明確使用 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 opperator
    myBuf = yourBuf;

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

請參閱

參考

C++ 關鍵字

this 指標的類型

引數對應和 this 指標