作为一个C程序员,想到初始化的重要性,很少想到清除的重要性
对于一个库,对于一个曾经用过的对象,如果忘记清除是不安全的
如果库可以修改硬件参数,或者屏幕显示字符,或者堆中分配内容
如果没有清除,对象不会消失
析构函数的语法与构造函数一样,用类的名字作为函数名
析构函数要加个代字号 ~,和构造函数区别
当对象超出它的作用域时,编译器会自动调用析构函数
对象的定义点处调用构造函数
析构函数调用的证据是对象的右边的括号
//: C06:Constructor1.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Constructors & destructors
#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;
}
Tree::~Tree() {
cout << "inside Tree 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 Tree creation" << endl;
t.printsize();
t.grow(4);
cout << "before closing brace" << endl;
}
cout << "after closing brace" << endl;
getchar();
} ///:~
析构函数在右边的括号处调用
输出
before opening brace
after Tree creation
Tree height is 12
before closing brace
inside Tree destructor
Tree height is 16
after closing brace