虚析构函数作用(代码)

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

#pragma once

class 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!


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值