析构函数

析构函数详解
本文介绍了析构函数的基本概念及其在C++程序中的应用。通过一个具体的树类实例演示了如何使用析构函数来释放资源,并解释了析构函数在对象生命周期结束时的自动调用机制。

析构函数

作用:释放内存

析构函数的名字与类名称是一样的,不同的就是在名字前面加(~),在程序中会被自动调用。

class X

{

public

~p();

};

用构造函数和析构函数实现一个程序:

#include<iostream>

using namespace std;

 

class tree

{

 

public:

tree (int d);

~tree ();

void grow(int years);

void print();

private:

int height;

};

tree ::tree(int d)

{

height = d;

}

tree ::~tree()

{

cout << "clear"<<endl;

print();

}

void tree :: grow(int years)

{

height +=years;

}

void tree :: print()

{

cout << "the height is :"<<height<< endl;

}

int main()

{

tree T(10);

T.print();

T.grow(2);

}

注:在执行T.grow时,析构函数被自动调用对内存块进行清除,从下面的运行结果可以充分体现。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值