本文简单介绍单继承模式时构造函数和析构函数的调用顺序,及基类析构函数为虚函数时的多态情况
实例代码,注释为运行结果:
1 #include<iostream> 2 3 class Base 4 { 5 public: 6 Base(int a, int b): x(a), y(b) { std::cout << "Base::Base()" << std::endl; } 7 virtual ~Base() { std::cout << "Base::~Base()" << std::endl; } 8 virtual void Show() { std::cout << "Base::Show() and x is " << x << ", y is " << y << std::endl; } 9 protected: 10 int x; 11 int y; 12 }; 13 14 class Derive: public Base 15 { 16 public: 17 Derive(int a, int b): Base(a, b) { std::cout << "Derive::Derive()" << std::endl; } 18 ~Derive() { std::cout << "Derive::~Derive()" << std::endl; } 19 void Show() { std::cout << "Derive::Show() and x is " << x << ", y is " << y << std::endl; } 20 }; 21 22 int main(void) 23 { 24 25 Base *b = new Derive(1, 2); // Base::Base() -> Derive::Derive() 26 b->Show(); // Derive::Show() and x is 1, y is 2 27 delete b; // Derive::~Derive() -> Base::~Base() 28 // when ~Base is not virtual 29 // delete b; Base::~Base() 30 31 Derive *d = new Derive(1, 2); // Base::Base() -> Derive::Derive() 32 d->Show(); // Derive::Show() and x is 1, y is 2 33 delete d; // Derive::~Derive() -> Base::~Base() 34 35 return 0; 36 }
由此可见:
1、当基类的含有非默认构造函数时,子类需要在初始化列表中调用基类构造函数或子类构造函数函数体中调用,即如子类不调用基类构造函数,编译器报错;
2、调用子类的析构函数时,会自动调用基类的析构函数,顺序为先子类,后基类。
3、基类的析构函数为虚函数时,可使用多态,顺序调用子类析构函数和基类析构函数。