首页 > 代码库 > 【虚】示例代码

【虚】示例代码

三.虚析构

#include <iostream>using namespace std;class Base{public:    virtual ~Base(){ cout<<"Base destructor\n"; }};class Derived:public Base{public:    Derived(){ iPtr = new int(0); }    ~Derived(){        cout <<"Derived destructor\n";        delete iPtr; //  这里会调用 基类 析构函数?!!!    }private:    int *iPtr;};void fun(Base *b){ delete b; }//delete会调用析构函数,这里调用派生类的析构void main(){    Base *b=new Derived(); //基类型指针d 指向派生类对象,分配了内存,就要在对象消失时 释放相应的内存                          //通过 基类指针b 删除 派生类对象    fun(b);}