C++快速入门 第二十八讲:多继承(multiple inheritance)

发布时间 2023-08-18 15:12:15作者: 一杯清酒邀明月
  1 多继承语法:
  2 
  3 //助教类既继承于老师类,又继承于学生类 
  4 class Assistant:public Teacher,public Student
  5 {
  6 };
  7 
  8 当遇到的问题无法只用一个“是一个”关系来描述的时候,就是多继承出场的时候。例即是学生,又是人,还是助教。
  9 
 10 #include <iostream>
 11 #include <string> 
 12 
 13 using namespace std;
 14 
 15 #include <string>
 16 //人类 
 17 class Person
 18 {
 19 public:
 20     Person(string theName);//构造函数,theName为类的输入参数 
 21     void introduce();
 22 protected:
 23     string name;
 24 };
 25 Person::Person(string theName)//构造函数实现 
 26 {
 27     name = theName;
 28 }
 29 void Person::introduce()//introduce()函数实现 
 30 {
 31     cout << "大家好,我是" << name << "。\n\n";
 32 }
 33 
 34 //老师类继承于人类 
 35 class Teacher:public Person
 36 {
 37 public:
 38     Teacher(string theName,string theClass);
 39     
 40     void teach();//教书 
 41     void introduce();
 42 protected:
 43     string classes;
 44 };
 45 Teacher::Teacher(string theName,string theClass):Person(theName)//老师的名字继承于人类中的名字 
 46 {
 47     classes = theClass;
 48 }
 49 void Teacher::teach()
 50 {
 51     cout<< name << ""<< classes << "。\n\n";
 52 }
 53 void Teacher::introduce()
 54 {
 55     cout<<"大家好,我是 "<< name <<" ,我教 "<< classes << "。\n\n";
 56 }
 57 
 58 //学生类继承于人类
 59 class Student:public Person 
 60 {
 61 public:
 62     Student(string theName,string theClass);
 63     
 64     void attendClass();//要上课 
 65     void introduce();
 66 protected:
 67     string classes;
 68 };
 69 Student::Student(string theName,string theClass):Person(theName)//学生名字继承于人类中的名字 
 70 {
 71     classes = theClass;
 72 }
 73 void Student::attendClass()
 74 {
 75     cout<< name <<"加入"<< classes << "学习。\n\n";
 76 }
 77 void Student::introduce()
 78 {
 79     cout<< "大家好,我是" << name << ",我在" << classes << "学习。\n\n";
 80 }
 81 
 82 //助教类既继承于老师类,又继承于学生类 
 83 class Assistant:public Teacher,public Student
 84 {
 85 public:
 86     Assistant(string theName,string classTeaching,string classAttending);
 87     
 88     void introduce();
 89 };
 90 Assistant::Assistant(string theName,string classTeaching,string classAttending):Teacher(theName, classTeaching),Student(theName,classAttending)
 91 {
 92 
 93 //多继承 助教既继承老师类,又继承学生类 
 94 
 95 }
 96 void Assistant::introduce()
 97 {
 98     cout << "大家好,我是" << Student::name << ".我教" << Teacher::classes << "";
 99     cout << "同时我在" << Student::classes << "学习。\n\n"; 
100 }
101 
102 int main()
103 {
104     Teacher teacher("小甲鱼","C++入门班");
105     Student student("迷途羔羊","C++入门班");
106     Assistant assistant("丁丁","C++入门班","C++进阶班");
107     
108     teacher.introduce();
109     teacher.teach();
110     
111     student.introduce();
112     student.attendClass();
113     
114     assistant.introduce();
115     assistant.teach();
116     assistant.attendClass();
117     
118     return 0;
119 }