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

c++ 虚拟析构函数

2012-07-09 00:01 246 查看
通过基类指针删除派生类对象,基类又没有虚析构函数,结果不可确定。(派生类的析构函数没有被调用,派生类的对象没有被回收)。如下是没有定义虚拟的析构函数。
#include <iostream>
using namespace std;

class Base
{
public:
Base( void )
{
cout << "Base::Base( )" << endl;
}

~Base( void ) //基类没有虚析构函数时

{
cout << "Base::~Base( )" << endl;
}
};

class Derived : public Base
{
public:
Derived( void )
{
m_pData = new int;
cout << "Derived::Derived( )" << endl;
}

~Derived( void )
{
delete m_pData;
m_pData = NULL;
cout << "Derived::~Derived( )" << endl;
}
private:
int* m_pData;
};

int main( void )
{
Derived* pD = new Derived;

Base* pB = pD;

//通过基类的指针去删除派生类的对象,而基类又没有虚析构函数时,结果将是不可确定的。

//(此处是派生类的析构函数没有被调用。)

delete pB;
pB = NULL;

system( "PAUSE" );
return EXIT_SUCCESS;
}

/*-------派生类的析构函数没有被调用,当然派生类的对象没有被回收
Base::Base( )
Derived::Derived( )
Base::~Base( )
请按任意键继续. . .

如果加上virtual ,就会输出:

/*-------派生类的析构函数没有被调用,当然派生类的对象没有被回收
Base::Base( )
Derived::Derived( )
Derived::~Derived()
Base::~Base( )
请按任意键继续. . .


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