虚析构函数的作用主要是当通过基类指针删除派生类对象时,调用派生类的析构函数(如果没有将不会调用派生类析构函数)

#include <iostream>

using namespace std;

class base
{
public:
base() { cout << "base()" << endl; }
virtual ~base() { cout << "~base()" << endl; }
}; class derived : public base
{
public:
derived () { cout << "derived ()" << endl; }
~derived () { cout << "~derived ()" << endl; }
}; int main()
{
base *test = new derived();
delete test;
}
05-06 16:55