析构函数
作用:释放内存
析构函数的名字与类名称是一样的,不同的就是在名字前面加(~),在程序中会被自动调用。
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时,析构函数被自动调用对内存块进行清除,从下面的运行结果可以充分体现。
析构函数详解
本文介绍了析构函数的基本概念及其在C++程序中的应用。通过一个具体的树类实例演示了如何使用析构函数来释放资源,并解释了析构函数在对象生命周期结束时的自动调用机制。
1734

被折叠的 条评论
为什么被折叠?



