您的位置:首页 > 编程语言 > C语言/C++

程序基石系列之自动调用析函数

2014-02-12 16:38 417 查看
当对象超了它的作用域时,编译器将自动调用析函数。即在对象的定义点处构造函数被调用,但析函数调用的惟一证据是包含此对象的右括号。
/*
* Constructors &Destructors
* Eclispe CDT
*/
#include <iostream>
using namespace std;

class Tree{
int height;
public:
Tree(int initialHeight);//Constructor
~Tree();//Destructor
void grow(int years);
void printsize();
};

Tree::Tree(int initialHeight){
height = initialHeight;
//cout<<"Initial Height:"<<height<<endl;
}

Tree::~Tree(){
cout<<"inside Tress destructor"<<endl;
printsize();
}

void Tree::grow(int years){
height +=years;
}

void Tree::printsize(){
cout<<"Tree height is "<<height<<endl;
}

int main(){
cout<<"before opening brace"<<endl;
{
Tree t(12);
cout<<"after Tress creation"<<endl;
t.printsize();
t.grow(4);
cout<<"before closing brace"<<endl;
}
cout<<"after closing brace"<<endl;
}
程序输出结果:before opening brace
after Tress creation
Tree height is 12
before closing brace
inside Tress destructor
Tree height is 16
after closing brace
可以看到析函数在包括它的右括号处被调用。

关于程序设计基石与实践更多讨论与交流,敬请关注本博客和新浪微博songzi_tea.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 析函数