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;
}