﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>C++博客-c++的新手,移动是我的方向</title><link>http://www.cppblog.com/david-new/</link><description>研究delphi有一段时间但是对c++还有待进步</description><language>zh-cn</language><lastBuildDate>Tue, 09 Jun 2026 18:55:38 GMT</lastBuildDate><pubDate>Tue, 09 Jun 2026 18:55:38 GMT</pubDate><ttl>60</ttl><item><title>构造函数和析构函数的例子</title><link>http://www.cppblog.com/david-new/archive/2006/05/22/7476.html</link><dc:creator>c++的新手</dc:creator><author>c++的新手</author><pubDate>Mon, 22 May 2006 02:24:00 GMT</pubDate><guid>http://www.cppblog.com/david-new/archive/2006/05/22/7476.html</guid><wfw:comment>http://www.cppblog.com/david-new/comments/7476.html</wfw:comment><comments>http://www.cppblog.com/david-new/archive/2006/05/22/7476.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/david-new/comments/commentRss/7476.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/david-new/services/trackbacks/7476.html</trackback:ping><description><![CDATA[#include "stdafx.h"
class tree{
	int height;
public:
	tree(int initalheight);  //声明构造函数,如果带有参数,则一般用来初始化变量
	~tree();                 //声明析构函数,一般不带任何参数
	void grow(int years);
	void printsize();
};                //这里的分号很起作用,如果忘记会产生莫名奇妙的编译错误

tree::tree(int initalheitht){      //定义构造函数,并初始化变量
	height=initalheitht;
}
tree::~tree(){                     //定义析构函数,
	puts("inside tree destructor");
	printsize();
}

void tree::grow(int years) {
	height+=years;
}

void tree::printsize(){
	printf("tree height is %d\n",height);
}

int _tmain(int argc, _TCHAR* argv[])
{
	puts("before opening brace");
	{
		tree t(12);
		puts("after tree creation");
		t.printsize();
		t.grow(4);
		puts("before closing brace");
	}               //执行到此处t的生命结束,系统将调用析构函数,释放对象
	                //在此如果想再调用t.printsize()会有编译错误
	puts("after closing brace");
	return 0;
}
/*   执行结果如下
before opening brace
after tree creation
tree height is 12
before closing brace
inside tree destructor
tree height is 16
after closing brace
*/
<img src ="http://www.cppblog.com/david-new/aggbug/7476.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/david-new/" target="_blank">c++的新手</a> 2006-05-22 10:24 <a href="http://www.cppblog.com/david-new/archive/2006/05/22/7476.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>