搜索
您的当前位置:首页正文

为什么基类的析构函数定义为虚函数

来源:易榕旅网

前提:
1:每个析构函数只会清理自己的成员(成员函数前没有virtual)。
2:可能是基类的指针指向派生类的对象,当析构一个指向派生类的成员的基类指针,这时程序不知道这么办,可能会造成内存的泄露,因此此时基类的析构函数要定义为虚函数;
基类指针可以指向派生类的对象(多态),如果删除该指针delete[]p,就会调用该指针指向的派生类的析构函数,而派生类的对象又会自动调基类的成员函数,这样就会把派生类的对象释放,如果基类的析构函数没有定义成虚函数,则编译器实现的静态绑定,在删除基类的指针,只会释放基类的析构函数而不会释放派生类的成员函数,此时会导致释放内存不完全,就会导致内存泄露的问题。
一:派生类指针指向派生类的对象

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

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

};
void Test()
{
    Driver*pd = new Driver;
    delete pd;
}

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

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

};
void Test()
{
   Base *pd = new Driver;
    delete pd;
}

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

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

};
void Test()
{
   Base *pd = new Driver;
    delete pd;
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Top