Latest web development tutorials

C++ 中的this 指針

C++ 類 & 對象 C++類&對象

在C++中,每一個對像都能通過this指針來訪問自己的地址。this指針是所有成員函數的隱含參數。因此,在成員函數內部,它可以用來指向調用對象。

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

下面的實例有助於更好地理解this 指針的概念:

#include <iostream>
 
using namespace std;

class Box
{
   public:
      // 构造函数定义
      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

C++ 類 & 對象 C++類&對象