# include<iostream>
using namespace std;
class Box{
public:
Box(double length=1.0,double width=2.0,double height=3.0) {
cout << "constructor called" << endl;
this -> length = length;
this -> width = width;
this -> height = height;
}//构造函数
~Box(){}//析构函数
Box* getAddress(){
return this;//通过this指针返回对象地址
}
double V(){
return length*width*height;
}
int compare(Box b){
return this->V() > b.V();
}
private:
double length;
double width;
double height;
};
int main(){
Box b1;
Box b2(2,3,4);
cout << b1.getAddress() << endl;
cout << b2.getAddress() << endl;
cout << b1.compare(b2) << endl;
cout << b2.V() << endl;
}
在 C++ 中,每一个对象都能通过 this 指针来访问自己的地址。this 指针是所有成员函数的隐含参数。因此,在成员函数内部,它可以用来指向调用对象。
我们可以通过this指针获得对象在内存中的地址。this指针总是指向“这个”对象,因此其指针的值不能被改变,也就是一个指针类型的常量。
在C++中构造函数的作用是在对象被创建时利用特定值构造对象,使对象保持一定的状态。
而析构函数的作用是用来完成对象被删除前的一些清理工作。