为什么基类析构函数一般写成虚函数
析构函数不是虚函数:
#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; }
执行结果: