先看如下一段程序:
#include <iostream> using namespace std;
class A1 { private: int m; public: A1(int i) { m = i; cout<<"A1 constructor. "<<m<<endl; } ~A1() { cout<<"A1 destructor. "<<m<<endl; } }; class A2 { private: int m; public: A2(int i) { m = i; cout<<"A2 constructor. "<<m<<endl; } ~A2() { cout<<"A2 destructor. "<<m<<endl; } }; class A3 { private: int m; public: A3() { cout<<"A3 constructor. "<<m<<endl; } ~A3() { cout<<"A3 destructor. "<<m<<endl; } };
class B:public A2,public A1,public A3 { A1 a1; A2 a2; A3 a3; public: B(int a,int b,int c,int d):A2(b),A1(a),a1(c),a2(d) { cout<<"B constructor. "<<endl; } ~B() { cout<<"B destructor. "<<endl; } };
int main() { B *b = new B(1,2,3,4); delete b; }
|
执行结果如下:
A2 constructor. 2
A1 constructor. 1
A3 constructor. 0 //windows下这是一随机树目,linux下为0,原因在于g++会自动把未初始化的变量初始化为0;
A1 constructor. 3
A2 constructor. 4
A3 constructor. 0 //同上
B constructor.
B destructor.
A3 destructor. 0 //同上
A2 destructor. 4
A1 destructor. 3
A3 destructor. 0 //同上
A1 destructor. 1
A2 destructor. 2
总结如下:
- 当定义一个子类对象时,首先调用其基类构造函数,再调用子类构造函数,接着再初始化成员变量。
- 如果有多个基类,则按继承顺序调用其构造函数。
- 析构函数的调用过程与构造函数相反。
阅读(2459) | 评论(0) | 转发(0) |