本文主要是介绍为什么C++基类析构函数写成虚函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
下面的代码举例:
// virtual.cpp : 定义控制台应用程序的入口点。
//#include "stdafx.h"
#include <string.h>
#define MAXLEN 128
class CEmployee{
public:
int m_ID;
char m_Name[MAXLEN];
char m_Depart[MAXLEN];
CEmployee(){
printf("CEmployee 类构造函数被调用了/n");
}
~CEmployee(){
printf("CEmployee 类析构函数被调用了/n");
getchar();
}
protected:
private:
};
class COperator:public CEmployee{
public:
char m_Password[MAXLEN];
COperator(){
strcpy(m_Name,"MR");
printf("COperator 子类的构造函数被调用了/n");
getchar();
}
~COperator(){
printf("COperator 子类析构函数被调用/n");
getchar();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CEmployee *oper = new COperator() ;
delete oper;
return 0;
}
函数的返回结果是:
可以看到值调用了父类的析构函数,而子类的析构函数没有被调用,那么可想而知,如果在子类的构造函数中对某个成员函数在堆空间中分配了空间,而之类没有被调用,是不是会造成内存泄漏呢?答案是肯定的,那有什么办法可以解决这种情况下出现的内存泄漏呢?那就是把父类的析构函数写为虚函数,看下面的代码:
// virtual.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <string.h>
#define MAXLEN 128
class CEmployee{
public:
int m_ID;
char m_Name[MAXLEN];
char m_Depart[MAXLEN];
CEmployee(){
printf("CEmployee 类构造函数被调用了/n");
}
virtual ~CEmployee(){
printf("CEmployee 类析构函数被调用了/n");
getchar();
}
protected:
private:
};
class COperator:public CEmployee{
public:
char m_Password[MAXLEN];
COperator(){
strcpy(m_Name,"MR");
printf("COperator 子类的构造函数被调用了/n");
getchar();
}
~COperator(){
printf("COperator 子类析构函数被调用/n");
getchar();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CEmployee *oper = new COperator() ;
delete oper;
return 0;
}
运行结果:
因此,在写父类的时候,最好将其析构函数写为虚函数。这样可以防止比较瘾避的内存泄漏。
这篇关于为什么C++基类析构函数写成虚函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!