关于虚
析构函数作用示例.
首先是一个main方法驱动
头文件如下:
#include "TestVirtualDestructor.h"
int main() {
	 Person *person = new Student;
	 delete person;
	return 0;
}
/**
 * 输出结果:
 *
 *1.没有使用虚析构函数的时候的输出:子类的析构函数没有调用.
调用Person的构造函数.
调用Student的构造函数.
调用Person的析构函数.
 */
相关的类文件如下:
/*
 * TestVirtualDestructor.h
 *
 *  Created on: 2011-10-12
 *      Author: banxi1988
 */
#include "common.h"
class Person{
public:
	Person(){
		cout<<"调用Person的构造函数."<<endl;
	};
	~Person(){
		cout<<"调用Person的析构函数."<<endl;
	}
};
class Student:public Person{
public:
	Student(){
		ptr = new int;
		cout<<"调用Student的构造函数."<<endl;
	}
	~Student(){
		delete ptr;
		cout<<"调用Student的析构函数."<<endl;
	}
private:
	int *ptr;
};
这个时候的输出结果,可以很明显的看出没有调用子类的析构函数.
而在子类也而在删除person实例时,其实需要释放它在堆上生成的一个ptr.
.
我们将~Person声明为virtual ~Person之后运行结果如下:
/**
 *
调用Person的构造函数.
调用Student的构造函数.
调用Student的析构函数.
调用Person的析构函数.
 */
所以析构函数,还是用虚的总是好的.
所以代码重构如下:
/*
 * TestVirtualDestructor.h
 *
 *  Created on: 2011-10-12
 *      Author: banxi1988
 */
#include "common.h"
class Person{
public:
	Person(){
		cout<<"调用Person的构造函数."<<endl;
	};
	 virtual ~Person(){
		cout<<"调用Person的析构函数."<<endl;
	}
};
class Student:public Person{
public:
	Student(){
		ptr = new int;
		cout<<"调用Student的构造函数."<<endl;
	}
	virtual ~Student(){
		delete ptr;
		cout<<"调用Student的析构函数."<<endl;
	}
private:
	int *ptr;
};