使用虚析构函数举例:
//本例演示析构函数需要被定义成虚函数的情况,注意构造函数是不可以被定义成虚函数的 #include<iostream> using namespace std; class Base{ public: ~Base(); //virtual ~Base(); }; Base::~Base(){ cout<<"Base destructor"<<endl; } class Derived : public Base{ private: int *p; public: Derived(); ~Derived(); //virtual ~Derived(); }; Derived::Derived(){ p = new int(0); } Derived::~Derived(){ cout<<"Derived destructor"<<endl; } void fun(Base *b){ delete b; } int main(){ Base *b = new Derived(); fun(b); //由于会直接调用基类,所以在派生类中分配的空间不会被释放掉,造成内存泄露 //解决方法是:将基类和派生类的析构函数声明为虚函数(即每行注释的代码) system("pause"); return 0; }