析构函数

来源:互联网 发布:网络推广宣传单 编辑:程序博客网 时间:2024/04/29 08:30

析构函数

作用:释放内存

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

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时,析构函数被自动调用对内存块进行清除,从下面的运行结果可以充分体现。


1 0
原创粉丝点击