在 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++ this 指針