以下说明继承类函数构造时,先构造基类;
析构基类时,若没加上virtual,只析构基类,不析构派生类;
析构派生类时,同时会析构基类;
1. 基类析构函数有virtual
#include <stdio.h> class Base { public: int a; Base(){ a=0; printf("base construct "); } virtual ~Base(){ printf("base delete "); } virtual void setA()=0; }; class A:public Base { public: A(){ a = 10; printf("A construct "); } ~A(){ printf("A class delete "); } virtual void setA() { a = 2; } }; int main() { Base *x = new A(); A *aClass = new A(); delete x; printf("--------------- "); delete aClass; return 0; }
运行结果:
2. 基类析构函数无virtual
class Base { public: int a; Base(){ a=0; printf("base construct "); } ~Base(){ printf("base delete "); } virtual void setA()=0; };
运行结果为: