非常感激我队友大爹提供的复习资料

注意:

  1. 这里并没有列出全部基类和成员对象, 由于Base3类只有默认构造函数, 不需要给它传递参数,因此, Base3以及Base3类成员对象mem3就不必列出。

  2. 其次, 基类名和成员对象名的顺序是随意的。这个派生类构造函数的函数体为空, 可见实际上只是起到了传递参数和调用基类及内嵌对象的作用。

关于执行顺序

  • 先调用基类的构造函数, 再调用内嵌对象的构造函数;
  • 基类构造函数的调用顺序 : 按照派生类定义时的顺序; (2–> 1–> 3)
  • 内嵌对象的调用顺序 : 按照成员在类中声明的顺序; (1–> 2–> 3)

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <bits/stdc++.h>
using namespace std;

class Base1{
private:
int ii;
public:
void show();
Base1(int i) { ii = i; cout << "Constructor Base1 " << i << endl; }
~Base1() { cout << "Destructor Base1 " << ii << endl; }
};

void Base1::show(){
cout << "Base1: " << ii << endl;
}

class Base2{
private:
int jj;
public:
void show();
Base2(int j) {jj = j; cout << "Constructor Base2 " << j << endl; }
~Base2() { cout << "Destructor Base2 " << jj << endl; }
};

void Base2::show(){
cout << "Base2: " << jj << endl;
}

class Base3{
public:
Base3() {cout << "Constructor Base3 * " << endl; }
~Base3() { cout << "Destructor Base3 *" << endl;}
};

class Derived : public Base2, public Base1, public Base3{
private:
Base1 mem1;
Base2 mem2;
Base3 mem3;
public:
Derived(int a, int b, int c, int d) : Base1(a), mem2(d), mem1(c), Base2(b) {}
void show();
};

void Derived::show(){
cout << "mem1: ";mem1.show();
cout << "mem2: ";mem2.show();
}

int main(void){
Derived obj(1, 2, 3, 4);
obj.Base1::show();
obj.Base2::show();
obj.show();
return 0;
}

/*
=====================
Constructor Base2 2
Constructor Base1 1
Constructor Base3 *
Constructor Base1 3
Constructor Base2 4
Constructor Base3 *
Base1: 1
Base2: 2
mem1: Base1: 3
mem2: Base2: 4
Destructor Base3 *
Destructor Base2 4
Destructor Base1 3
Destructor Base3 *
Destructor Base1 1
Destructor Base2 2
=====================
*/