程序基石系列之自动调用析函数
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.
/*
* 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#应用程序中自动调用相应程序打开任意文档类型(如果本地已安装该软件)
- 小程序开发系列(八)利用SQL实现access_token的自动通知
- 调用信号处理程序被捕捉的信号自动地加到进程的当前信号屏蔽字中signal() sigpending()
- Reporting Service Tips 101(#4) - 使用RS实现报表的自动生成以及在程序中调用RS
- [转贴]Windows批处理调用程序后如何自动退出
- linux下用gdb实现程序宕机时自动打印调用堆栈
- Windows批处理调用程序后如何自动退出
- python程序如何在生产和测试环境自动调用对应的配置文件
- Windows7 PSR通过程序调用并自动开始记录
- VC程序调用MATCOM导致进程不自动结束的解决办法
- 微信小程序系列-1、调用本地接口
- Eclipse编写和调试Applet程序,调试的时候Eclipse会自动调用Java "小程序查看程序",而不用嵌入到网页中查看运行效果。
- 程序设计基石与实践系列之能让你成为Top程序员的十个C语言资源
- 使用JAVA远程调用导致程序自动down掉,jdk1.5的debug模式系统漏洞
- VB 调用打开各种文件(自动查找使用默认的程序)
- 程序基石系列之C++多态的前提条件
- 程序设计基石与实践系列之最短的崩溃C语言程序
- 程序基石系列之C++多态的前提条件
- VB.net 调用OutLook发邮件(程序自动添加附件)
- 程序入口自动调用 controller 的方法