1. 程式人生 > >C++(三十) — this 指針

C++(三十) — this 指針

system pri 訪問類 pau pause -s 地址 pre int()

1、如何區分多個對象調用同一個類函數?

  類外部訪問類成員,必須用對象來調用。一個類的所有對象在調用的成員函數,都執行同一段代碼,那成員函數如何區分屬於哪個對象呢?

  在對象調用成員函數時,除接收實參外,還接受一個對象的地址。也就是隱含參數:this 指針(編譯器自動實現).

  this 指針指出,成員函數當前所操作的數據所屬的對象。不同對象調用成員函數時,this指針指向不同對象。

class test
{
public:
    // 
    test(int a, int b)  // test(test *this, int a, int b)
    {
        this
->a = a; this->b = b; cout << "構造函數執行" << endl; } void print() { cout << a << endl; cout << this->b << endl; } private: int a; int b; }; int main() { test t(1,2); t.print(); // print(&t )
system("pause"); return 0; }

  

C++(三十) — this 指針