您的位置:首页 > 编程语言 > C语言/C++

为什么C++基类析构函数写成虚函数

2015-07-25 15:12 399 查看
下面的代码举例:

// 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;

}

运行结果:





因此,在写父类的时候,最好将其析构函数写为虚函数。这样可以防止比较瘾避的内存泄漏。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: