您的位置:首页 > 其它

派生类构造函数的执行顺序

2017-04-05 22:21 190 查看
派生类构造函数的执行顺序
 


 

 

下面给出一个例子

 

代码:

1 #include <iostream>
2
3 using namespace std;
4
5
6 //打印函数名辅助宏
7 #define PRINT_FUNC_NAME()\
8     cout << __FUNCTION__ << endl;
9
10
11 //构造及析构函数声明与实现辅助宏
12 #define DE_AND_CONSTRUCTOR( className )\
13 public:\
14     className(int a)\
15     :m_a(a)\
16     {\
17         PRINT_FUNC_NAME()\
18     }\
19     virtual ~className()\
20     {\
21         PRINT_FUNC_NAME()\
22     }\
23 private:\
24     int m_a;
25
26
27 class Base1
28 {
29     DE_AND_CONSTRUCTOR(Base1)
30 };
31
32 class Base2
33 {
34     DE_AND_CONSTRUCTOR(Base2)
35 };
36
37 class Base3
38 {
39     DE_AND_CONSTRUCTOR(Base3)
40 };
41
42 class Member1
43 {
44     DE_AND_CONSTRUCTOR(Member1)
45 };
46
47 class Member2
48 {
49     DE_AND_CONSTRUCTOR(Member2)
50 };
51
52
53
54 class Derived: public Base1, public Base2, public Base3
55 {
56 public:
57     Derived()//注意此处的顺序与执行的顺序无关
58         :Base3(0), m_Member1(0), Base1(0), Base2(0),m_Member2(0)
59     {
60         PRINT_FUNC_NAME()
61     }
62     virtual ~Derived()
63     {
64         PRINT_FUNC_NAME()
65     }
66
67 private:
68     Member1 m_Member1;
69     Member2 m_Member2;
70 };
71
72
73
74 int main()
75 {
76     Derived mDerived;
77
78     return 0;
79 }


 

运行结果:

 


 

参考:C++语言程序设计(第4版) 清华大学 郑莉 【第七章 7.4 派生类的构造和析构函数】
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: