C++编程总结之虚函数的使用

对于一个单一的类来说,析构函数是不是虚函数,其没有实质性的意义。但是当当前类作为基类的时候,基类的析构函数是不是虚函数则会对程序带来不同程度的影响。
看下下面的代码运行结果:
#include<iostream>
using namespace std;
class Base
{
public:
	Base()
	{
		cout << "Base:Constructor" <<endl;
	}
	~Base()
	{
		cout << "Base:Destructor" << endl;
	}
};

class DerivedA:public Base
{
public:
	DerivedA()
	{
		cout << "DerivedA:Constructor" <<endl;
	}
	~DerivedA()
	{
		cout << "DerivedA:Destructor" << endl;
	}
};

class DerivedB:public DerivedA
{
public:
	DerivedB()
	{
		cout << "DerivedB:Constructor" <<endl;
	}
	~DerivedB()
	{
		cout << "DerivedB:Destructor" <<endl;
	}
};

int main()
{
	Base* tmp = new DerivedA();
	delete tmp;
	return 0;
}

运行结果为:


运行结果大家估计看的出来,当析构函数为非虚函数时,delete tmp的时候,只去调用了基类的析构函数,并没有调用派生类的析构函数。
下面基类的析构函数使用需虚析构试试看结果如何:
#include<iostream>
using namespace std;
class Base
{
public:
	Base()
	{
		cout << "Base:Constructor" <<endl;
	}
	virtual ~Base()
	{
		cout << "Base:Destructor" << endl;
	}
};

class DerivedA:public Base
{
public:
	DerivedA()
	{
		cout << "DerivedA:Constructor" <<endl;
	}
	~DerivedA()
	{
		cout << "DerivedA:Destructor" << endl;
	}
};

class DerivedB:public DerivedA
{
public:
	DerivedB()
	{
		cout << "DerivedB:Constructor" <<endl;
	}
	~DerivedB()
	{
		cout << "DerivedB:Destructor" <<endl;
	}
};

int main()
{
	Base* tmp = new DerivedA();
	delete tmp;
	return 0;
}

运行结果为:

这个时候,函数调用delete tmp的时候,先调用了派生类的析构函数,然后调用了基类的析构函数。

通常情况下,一个类的析构函数中,总是去处理一些需要释放内存资源的工作,而当析构函数没有被正确调用的时候,那么可能会造成本该释放的内存在程序结束的时候不被释放,从而造成内存的泄露。当数据量大的时候可能会造成很大的损失。并且对于一个C++程序员,时刻保证程序不出现内存泄露,使我们必须时刻注意的问题。
综上所述,当我们需要把当前类作为基类使用的时候,我们必须注意析构函数虚化的处理。当然当不做基类的时候,我们可以不去设置虚析构。


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值