为什么基类析构函数一般写成虚函数

析构函数不是虚函数:

#include <iostream>
 
using namespace std;
 
class Parent
{
    public:
        Parent()
        {
            cout << "父类构造函数" << endl;
        }
        ~Parent()
        {
            cout << "父类析构函数" << endl;
        }
};
 
class Son : public Parent
{
    public:
        Son()
        {
            cout << "子类构造函数" << endl;
        }
        ~Son()
        {
            cout << "子类析构函数" << endl;
        }
};
 
int main()
{
    Parent *p = new Son();
    delete p;
    p = nullptr;
 
    return 0;
}

执行结果:

析构函数是虚函数:

#include <iostream>
 
using namespace std;
 
class Parent
{
    public:
        Parent()
        {
            cout << "父类构造函数" << endl;
        }
        virtual ~Parent()
        {
            cout << "父类析构函数" << endl;
        }
};
 
class Son : public Parent
{
    public:
        Son()
        {
            cout << "子类构造函数" << endl;
        }
        ~Son()
        {
            cout << "子类析构函数" << endl;
        }
};
 
int main()
{
    Parent *p = new Son();
    delete p;
    p = nullptr;
 
    return 0;
}

执行结果:

 

posted @ 2023-04-21 18:00  小丑_jk  阅读(12)  评论(0编辑  收藏  举报