1.如果类A可能会被继承,那么A的析构函数一定要被设置为virtual虚函数;
原因:如果基类的析构函数不是虚函数,当创建一个基类指针指向一个派生类对象,当释放此基类指针时,子类的析构函数不会被调用;
如下:
class CFather { public: CFather(); virtual ~CFather(); public: virtual void test(); //virtual void getHouse() = 0; public: int b; static const int c = 5; };
CFather::CFather() { infof("CFather...create! g_test:%d ", g_test++); } CFather::~CFather() { infof("~CFather...destory "); } void CFather::test() { infof("CFather...test "); }
class CChild : public CFather { public: CChild(); ~CChild(); public: void test(); virtual void getHouse(); private: int e; };
CChild::CChild() { infof("CChild...create:g_test:%d ", g_test++); } CChild::~CChild() { infof("~CChild...destory "); } void CChild::test() { infof("CChild...test "); } void CChild::getHouse() { infof("CChild getHouse "); }
int main() { Infra::setPrintLogLevel(6); CFather * cpt = new CChild; delete cpt; return 0; }
输出结果:
CFather...create! g_test:100 CChild...create:g_test:20 ~CChild...destory ~CFather...destory