0%

C++ 多继承

多继承体系下构造函数的调用

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
struct Student {
int m_score;
Student(int score) : m_score(score) {}
void study() {
cout << "student:study() score = "<< m_score << endl;
}
};

struct Worker {
int m_salary;
Worker(int salary) : m_salary(salary) {};
void work() {
cout << "worker:: work salary = " << m_salary << endl;
}
};

struct Underground : Student, Worker {
int m_grade;
Underground(int score, int salary, int grade) :m_grade(grade),
Student(score), Worker(salary) {}
void play() {
cout << "Unerground::play grade = " << m_grade << endl;
}
};

多继承-虚函数

如果子类继承的多个父类都有虚函数,那么子类对象就会产生对应的多个虚表

菱形继承

菱形继承带来的问题:
最底下子类从基类继承的成员变量冗余、重复

虚继承

虚继承可以解决菱形继承存在的问题
最上层的类是虚基类

1
2
3
4
5
6
7
8
9
10
11
12
13
struct Person {
int m_age;
};
struct Student : virtual Person {
int m_score;
};
struct Worker : virtual Person {
int m_salary;
};

struct Undergraduate : Student, Worker {
int m_grade;
};

多继承的应用

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
class JobBaomu {
public:
virtual void clean() = 0;
virtual void cook() = 0;
};
class JobTeacher {
public:
virtual void playfootball() = 0;
virtual void playbaseball() = 0;
};

class Student : public JobTeacher, public JobBaomu{
int m_score;
public:
void clean() {

}
void cook() {

}
void playfootball() {

}
void playbaseball() {

}
};

class Worker : JobTeacher{
int m_salary;
void playfootball() {

}
void playbaseball() {

}
};

求大佬赏个饭