C++多继承
发表于:2024-12-13 | 分类: C++
字数统计: 444 | 阅读时长: 2分钟 | 阅读量:

C++多继承

语法

1
2
3
class D: public A, private B, protected C{
//类D新增加的成员
}

构造

  • 子类构造会按照继承顺序默认调用父类的无参构造
  • 显式调用父类的构造(列表初始化),与书写顺序无关,初始化顺序依然由继承顺序决定
  • 析构执行顺序与构造执行顺序相反
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
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <iostream>
using namespace std;

// 基类
class BaseA
{
public:
BaseA()
{
cout << "BaseA constructor" << endl;
}
BaseA(int a, int b);
~BaseA();

protected:
int m_a;
int m_b;
};
BaseA::BaseA(int a, int b) : m_a(a), m_b(b)
{
cout << "BaseA constructor" << endl;
}
BaseA::~BaseA()
{
cout << "BaseA destructor" << endl;
}

// 基类
class BaseB
{
public:
BaseB()
{
cout << "BaseB constructor" << endl;
}
BaseB(int c, int d);
~BaseB();

protected:
int m_c;
int m_d;
};
BaseB::BaseB(int c, int d) : m_c(c), m_d(d)
{
cout << "BaseB constructor" << endl;
}
BaseB::~BaseB()
{
cout << "BaseB destructor" << endl;
}

// 派生类,构造执行顺序是A,B和子类
class Derived : public BaseA, public BaseB
{
public:
Derived()
{
cout << "Derived constructor" << endl;
}
Derived(int a, int b, int c, int d, int e);
~Derived();

public:
void show();

private:
int m_e;
};

// 派生类构造函数,构造执行顺序依然是A,B和子类
Derived::Derived(int a, int b, int c, int d, int e) : BaseB(a, b), BaseA(c, d), m_e(e)
{
cout << "Derived constructor" << endl;
}
Derived::~Derived()
{
cout << "Derived destructor" << endl;
}
void Derived::show()
{
cout << m_a << ", " << m_b << ", " << m_c << ", " << m_d << ", " << m_e << endl;
}

int main()
{
Derived obj1;
cout << "--------------------" << endl;
Derived obj(1, 2, 3, 4, 5);
obj.show();
return 0;
}

对于相同的函数和属性,依旧使用::来控制访问

上一篇:
C++虚继承
下一篇:
C++继承