构造函数与析构函数


# 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++中构造函数的作用是在对象被创建时利用特定值构造对象,使对象保持一定的状态。
而析构函数的作用是用来完成对象被删除前的一些清理工作。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值