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