当对象超了它的作用域时,编译器将自动调用析函数。即在对象的定义点处构造函数被调用,但析函数调用的惟一证据是包含此对象的右括号。
/*
* 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.