虚析构函数作用(代码)
来源:互联网 发布: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
- 虚析构函数作用(代码)
- _splitpath函数 具体作用看代码
- 虚析构函数作用分析(转)
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数作用
- 虚析构函数的作用
- 虚析构函数作用
- 虚析构函数作用
- 虚析构函数作用
- Android Studio如何设置代码自动提示
- SpringSecurity3.2y启动报Exception starting filter springSecurityFilter错误解决办法
- Maximum Product Subarray
- ADB
- hdu_1698Just a Hook线段树_区间修改
- 虚析构函数作用(代码)
- vmware10中开启Intel VT-x
- slidingMenu使用API
- EJB实体Bean如何和数据库中表关联?
- xcode搜索方法调用者快捷键
- java反射自我总结
- CCSprite详解
- 关于C++ const 的全面总结
- 使用ReadFile()时如何更改ReadFile的timeout