C++中的“this”指針

C++中的“this”指針

要理解“this”指針,重要的是要了解對象如何看待類的函數和數據成員。

1)每個對象都有自己的數據成員副本。

2)所有人都訪問與代碼段中相同的函數定義。

意味著每個對象都有自己的數據成員副本,並且所有對象共享成員函數的單個副本。

現在的問題是,如果每個成員函數只有一個副本並且被多個對象使用,那麼如何訪問和更新適當的數據成員?

編譯器提供一個隱式指針以及函數名“this”。

“ this”指針作為隱藏參數傳遞給所有非靜態成員函數調用,並且可用作所有非靜態函數主體中的局部變量。“ this”指針在靜態成員函數中不可用,因為可以在沒有任何對象(帶有類名)的情況下調用靜態成員函數。

對於X類,此指針的類型為“ X *”。另外,如果X的成員函數聲明為const,則此指針的類型為“ const X *”。

C++通過調用以下代碼讓對象銷燬自身:

<code>delete this;/<code>

以下是使用“ this”指針的情況:

1)當本地變量的名稱與成員的名稱相同時

<code>#include 
using namespace std; 
  
/* local variable is same as a member's name */
class Test 
{ 
private: 
   int x; 
public: 
   void setX (int x) 
   { 
       // The 'this' pointer is used to retrieve the object's x 
       // hidden by the local variable 'x' 
       this->x = x; 
   } 
   void print() { cout << "x = " << x << endl; } 
}; 
  
int main() 
{ 
   Test obj; 
   int x = 20; 
   obj.setX(x); 
   obj.print(); 
   return 0; 
} /<code>

輸出:

<code>x = 20/<code>

對於構造函數,當參數名稱與成員名稱相同時,也可以使用初始化程序列表。

2)返回對調用對象的引用

<code>/* Reference to the calling object can be returned */ 
Test& Test::func () 
{ 
   // Some processing 
   return *this; 
}  /<code>

當返回對本地對象的引用時,返回的引用可用於鏈接單個對象上的函數調用。

<code>#include 
using namespace std; 
  
class Test 
{ 
private: 
  int x; 
  int y; 
public: 
  Test(int x = 0, int y = 0) { this->x = x; this->y = y; } 
  Test &setX(int a) { x = a; return *this; } 
  Test &setY(int b) { y = b; return *this; } 
  void print() { cout << "x = " << x << " y = " < 
< y << endl; } }; int main() { Test obj1(5, 5); // Chained function calls. All calls modify the same object // as the same object is returned by reference obj1.setX(10).setY(20); obj1.print(); return 0; } /<code>

輸出:

<code>x = 10 y = 20/<code>


分享到:


相關文章: