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

本文通过一个 C++ 的 Tree 类实例演示了析构函数如何在对象超出其作用域时被自动调用的过程。当 Tree 对象 t 在代码块结束时,其析构函数被触发并打印当前树的高度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

/*
 *  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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值