如下說明繼承類函數構造時,先構造基類;函數
析構基類時,若沒加上virtual,只析構基類,不析構派生類;blog
析構派生類時,同時會析構基類;繼承
1. 基類析構函數有virtualio
#include <stdio.h> class Base { public: int a; Base(){ a=0; printf("base construct\n"); } virtual ~Base(){ printf("base delete\n"); } virtual void setA()=0; }; class A:public Base { public: A(){ a = 10; printf("A construct\n"); } ~A(){ printf("A class delete\n"); } virtual void setA() { a = 2; } }; int main() { Base *x = new A(); A *aClass = new A(); delete x; printf("---------------\n"); delete aClass; return 0; }
運行結果:class
2. 基類析構函數無virtualim
class Base { public: int a; Base(){ a=0; printf("base construct\n"); } ~Base(){ printf("base delete\n"); } virtual void setA()=0; };
運行結果爲:d3