问题的由来
#include <iostream> using namespace std; class Point { public: Point( ) { } ~Point() { cout<<"executing Point destructor"<<endl; } }; class Circle:public Point { public: Circle( ) { } ~Circle( ) { cout<<"executing Circle destructor"<<endl; } private: int radius; }; int main( ) { Point *p=new Circle; delete p; return 0; }
使用虚析构函数
#include <iostream> using namespace std; class Point { public: Point( ) { } virtual ~Point() { cout<<"executing Point destructor"<<endl; } }; class Circle:public Point { public: Circle( ) { } ~Circle( ) { cout<<"executing Circle destructor"<<endl; } private: int radius; }; int main( ) { Point *p=new Circle; delete p; return 0; }