我们直接上案例:
// 虚析构函数.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
#pragma warning(disable:4996)
class A{
public:
A(){
p = new char[20];
strcpy(p,"obja");
printf("A()\n");
}
~A(){
delete[]p;
printf("~A()\n");
}
private:
char *p;
};
class B:public A{
public:
B(){
p = new char[20];
strcpy(p,"objb");
printf("B()\n");
}
~B(){
delete[]p;
printf("~B()\n");
}
private:
char *p;
};
class C :public B{
public:
C(){
p = new char[20];
strcpy(p, "objc");
printf("C()\n");
}
~C(){
delete[]p;
printf("~C()\n");
}
private:
char *p;
};
void howtoDelete(A *base){
delete base;
}
int _tmain(int argc, _TCHAR* argv[])
{
C *myC = new C;//new出来一个对象
howtoDelete(myC);//delete掉这个对象
return 0;
}
这个时候执行的结果是:
我们看到并没有执行B和A的析构函数。仅仅执行了父类的析构函数。因为这个时候没有虚函数,是静态联编,因此是什么类型就调用什么方法,不会根据类型兼容性原则来
当我们想通过父类指针 把所有的子类对象的 析构函数 都执行一遍
意思就是想通过父类指针 释放所有的子类资源
这种情况 只能使用虚析构函数。
// 虚析构函数.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
#pragma warning(disable:4996)
class A{
public:
A(){
p = new char[20];
strcpy(p,"obja");
printf("A()\n");
}
virtual ~A(){
delete[]p;
printf("~A()\n");
}
private:
char *p;
};
class B:public A{
public:
B(){
p = new char[20];
strcpy(p,"objb");
printf("B()\n");
}
~B(){
delete[]p;
printf("~B()\n");
}
private:
char *p;
};
class C :public B{
public:
C(){
p = new char[20];
strcpy(p, "objc");
printf("C()\n");
}
~C(){
delete[]p;
printf("~C()\n");
}
private:
char *p;
};
void howtoDelete(A *base){
delete base;
}
int _tmain(int argc, _TCHAR* argv[])
{
C *myC = new C;//new出来一个对象
howtoDelete(myC);//delete掉这个对象
//detele myC;//也可以直接通过子类对象释放资源 不需要写virtual
return 0;
}