C++ this 指標



this 指標

C++ 中的每個物件都可以透過一個稱為this指標的重要指標訪問其自身的地址。this指標是所有成員函式的隱式引數。因此,在成員函式內部,this 可以用來引用呼叫該函式的物件。

友元函式沒有this指標,因為友元不是類的成員。只有成員函式才有this指標。

this 指標示例

讓我們嘗試以下示例來理解 this 指標的概念:

#include <iostream>
 
using namespace std;

class Box {
   public:
      // Constructor definition
      Box(double l = 2.0, double b = 2.0, double h = 2.0) {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
      }
      double Volume() {
         return length * breadth * height;
      }
      int compare(Box box) {
         return this->Volume() > box.Volume();
      }
      
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

int main(void) {
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

   if(Box1.compare(Box2)) {
      cout << "Box2 is smaller than Box1" <<endl;
   } else {
      cout << "Box2 is equal to or larger than Box1" <<endl;
   }
   
   return 0;
}

當以上程式碼編譯並執行時,會產生以下結果:

Constructor called.
Constructor called.
Box2 is equal to or larger than Box1

使用 this 指標返回呼叫物件的引用

要實現鏈式函式呼叫,您需要呼叫物件的引用。您可以使用“this”指標返回呼叫物件的引用。

語法

以下是語法:

Test& Test::func ()
{
   return *this;
}

示例

以下示例演示瞭如何返回對呼叫物件的引用

#include <iostream>
using namespace std;

class Coordinates {
 private:
  int latitude;
  int longitude;

 public:
  Coordinates(int lat = 0, int lon = 0) {
    this->latitude = lat;
    this->longitude = lon;
  }

  Coordinates& setLatitude(int lat) {
    latitude = lat;
    return *this;
  }

  Coordinates& setLongitude(int lon) {
    longitude = lon;
    return *this;
  }

  void display() const {
    cout << "Latitude = " << latitude << ", Longitude = " << longitude << endl;
  }
};

int main() {
  Coordinates location(15, 30);

  // Chained function calls modifying the same object
  location.setLatitude(40).setLongitude(70);

  location.display();
  return 0;
}

當以上程式碼編譯並執行時,會產生以下結果:

Latitude = 40, Longitude = 70
廣告