虚析构函数作用(代码)

来源:互联网 发布:java内部类 编辑:程序博客网 时间:2024/06/14 09:43

1.在没有虚析构函数的情况下

#pragma onceclass CPointX{public:CPointX(void);// virtual ~CPointX(void);~CPointX(void);int getX(){return m_x;}int getY(){return m_y;}void setX(int x){m_x = x;}void setY(int y){m_y = y;}protected:int m_x;int m_y;};
#include "StdAfx.h"#include "PointX.h"CPointX::CPointX(void){printf("point construct!\n");m_x = 0;m_y = 0;}CPointX::~CPointX(void){printf("point destruct!\n");}

#pragma once#include "pointx.h"class CColorPointX :public CPointX{public:CColorPointX(void);// virtual ~CColorPointX(void);~CColorPointX(void);protected:int m_color;};

CColorPointX::CColorPointX(void){printf("color point construct!\n");m_color = 0;}CColorPointX::~CColorPointX(void){printf("color point destruct!\n");}

main函数如下:

int _tmain(int argc, _TCHAR* argv[]){CColorPointX *pline = new CColorPointX();assert(pline != NULL);delete pline;pline = NULL;// CPointX* ppt = new CColorPointX();// delete ppt;return 0;}


输出结果如下:

point construct!

color point construct!

color point destruct!

point destruct!


2.将上述两个类中的析构函数改为虚析构函数,main函数不变,输出结果如下:

point construct!

color point construct!

color point destruct!

point destruct!

3.不使用虚析构函数,main函数如下:

int _tmain(int argc, _TCHAR* argv[]){// CColorPointX *pline = new CColorPointX();// assert(pline != NULL);// // delete pline;// pline = NULL;CPointX* ppt = new CColorPointX();delete ppt;return 0;}

输出结果:

point construct!

color point construct!

point destruct!

4.使用虚析构函数,main函数同3,输出结果如下:

point construct!

color point construct!

color point destruct!

point destruct!


总结:虚析构函数解决了使用基类指针删除派生类对象的问题。


0 0