C++ 基类的析构函数为什么需要定义为虚函数

主要是因为当通过父类的指针或引用指向子类的对象时,删除子类时父类的析构函数不能被调用造成内存泄露

1.当基类的引用指向基类的对象

#include<iostream>
#include<cstring>
#include<cstdlib>
using  namespace std ;

class Base
{
public:
    Base()
    {

        cout << "基类的构造函数被调用了" << endl;

    }
     ~Base()
    {

        cout << "基类的析构函数被执行了" <<endl;
    }

};

class Derived :public Base
{
public:
    Derived(char str[] = "")
    {
        if (str == NULL)
        {
            _Dstr = new char[1];
            *_Dstr = '\0';
        }
        else
        {
            _Dstr = new char [strlen(str) + 1];
            strcpy(_Dstr, str);
        }
        cout << "派生类的构造函数被调用了" << endl;

    }
    ~Derived()
    {
        if (_Dstr != NULL)
        {
            delete [] _Dstr;
            _Dstr = NULL;
        }
        cout << "派生类的析构函数被执行了" <<endl;
    }
private:
    char *_Dstr;
};


void test()
{
    Base B1;
    Base & b = B1;   //基类的引用或指针指向基类对象。
}

 
 
void test()
{
	Base B1;
	Base & b = B1;   //基类的引用或指针指向基类对象。
}
 
 
int main()
{
	test();
 
	cout << "hello..." <<endl;
	return 0;
}
程序的运行结果:

基类的构造函数被调用了
基类的析构函数被执行了
hello...

2.当基类的引用指向派生类的对象(基类是一个抽象类)

#include<iostream>
using  namespace std ;

class Abstract
{
public:
    virtual ~Abstract() = 0;

};

 Abstract:: ~Abstract()
{
    cout << "抽象类的析构函数被执行了" <<endl;
};

class Derived: public Abstract
{
public:
    Derived()
    {
        cout << "派生类的构造函数被执行了" <<endl;
    }
    ~Derived()
    {
        cout << "派生类的析构函数被执行了" << endl;
    }
};

void test()
{
    Derived d;
}

int main()
{
    test();

    cout << "hello..." <<endl;
    return 0;
}

程序的运行结果:

派生类的构造函数被执行了
派生类的析构函数被执行了
抽象类的析构函数被执行了
hello...

总结:

  当基类的对象含有指针成员,需要在删除对象时清除申请的内存单元,如果基类析构对象得不到调用将会造成申请的内存单元得不到回收,造成内存的泄露。

猜你喜欢

转载自blog.csdn.net/yetaibing1990/article/details/84892014