通过虚继承某个基类,就是在告诉编译器:从当前这个类再派生出来的子类只能拥有那个基类的一个实例。
虚继承的语法:
1 class Teacher:virtual public Person 2 3 { 4 5 }
这样做的话便可以让Student和Teacher类都虚继承自Person类,编译器将确保从Student和Teacher类再派生出来的子类只能拥有一份Person类的属性。
实例:虚继承应用
1 #include <iostream> 2 #include <string> 3 //虚继承可以让Student和Teacher类都虚继承自Person类, 4 //编译器将确保从Student和Teacher类再派生出来的子类只能拥有一份Person类的属性。 5 using namespace std; 6 7 #include <string> 8 //人类 9 class Person 10 { 11 public: 12 Person(string theName);//构造函数,theName为类的输入参数 13 void introduce(); 14 protected: 15 string name; 16 }; 17 Person::Person(string theName)//构造函数实现 18 { 19 name = theName; 20 } 21 void Person::introduce()//introduce()函数实现 22 { 23 cout << "大家好,我是" << name << "。\n\n"; 24 } 25 26 //老师类继承于人类 27 class Teacher:virtual public Person//虚继承,再有类继承Teacher类时,将只拥有一份Person类的属性。 28 { 29 public: 30 Teacher(string theName,string theClass); 31 32 void teach();//教书 33 void introduce(); 34 protected: 35 string classes; 36 }; 37 Teacher::Teacher(string theName,string theClass):Person(theName)//老师的名字继承于人类中的名字 38 { 39 classes = theClass; 40 } 41 void Teacher::teach() 42 { 43 cout<< name << " 教 "<< classes << "。\n\n"; 44 } 45 void Teacher::introduce() 46 { 47 cout<<"大家好,我是 "<< name <<" ,我教 "<< classes << "。\n\n"; 48 } 49 50 //学生类继承于人类 51 class Student:virtual public Person//虚继承,再有类继承Student类时,将只拥有一份Person类的属性 52 { 53 public: 54 Student(string theName,string theClass); 55 56 void attendClass();//要上课 57 void introduce(); 58 protected: 59 string classes; 60 }; 61 Student::Student(string theName,string theClass):Person(theName)//学生名字继承于人类中的名字 62 { 63 classes = theClass; 64 } 65 void Student::attendClass() 66 { 67 cout<< name <<"加入"<< classes << "学习。\n\n"; 68 } 69 void Student::introduce() 70 { 71 cout<< "大家好,我是" << name << ",我在" << classes << "学习。\n\n"; 72 } 73 74 //助教类既继承于老师类,又继承于学生类 75 class Assistant:public Teacher,public Student 76 { 77 public: 78 Assistant(string theName,string classTeaching,string classAttending); 79 80 void introduce(); 81 }; 82 Assistant::Assistant(string theName,string classTeaching,string classAttending) 83 :Teacher(theName, classTeaching),Student(theName,classAttending),Person(theName) 84 //由于虚继承,Teacher和Student都不能拥有Person类中的属性和方法 85 //只能由Person类自己给出 86 { 87 //多继承 助教既继承老师类,又继承学生类 88 } 89 void Assistant::introduce() 90 { 91 cout << "大家好,我是" << Student::name << ".我教" << Teacher::classes << ","; 92 cout << "同时我在" << Student::classes << "学习。\n\n"; 93 } 94 95 int main() 96 { 97 Teacher teacher("小甲鱼","C++入门班"); 98 Student student("迷途羔羊","C++入门班"); 99 Assistant assistant("丁丁","C++入门班","C++进阶班"); 100 101 teacher.introduce(); 102 teacher.teach(); 103 104 student.introduce(); 105 student.attendClass(); 106 107 assistant.introduce(); 108 assistant.teach(); 109 assistant.attendClass(); 110 111 return 0; 112 }标签:入门,继承,子类,C++,Person,第二十九,Student,theName,Teacher From: https://www.cnblogs.com/ybqjymy/p/17640564.html