虚继承(virtual inheritance)
由来
-
在使用多继承方法的过程中,当两个基类具有相同的属性,(如name属性),多继承自它们的子类也会具有两个该属性,会产生矛盾,因此我们需要使用虚继承来解决。
-
通过虚继承某个基类,就是在告诉编译器:从当前这个类派生出来的子类只能拥有这个基类的一个实例。
语法
class Teacher : virtual public Person
{
...
}
继上节课例子,让student类和teacher类都虚继承person类,编译器将确保从这两个类多继承出来的新的子类只拥有一份Person类的属性。
TIPS
-
在添加虚继承时,要注意对多继承出来的类的构造函数的书写,调用构造方法要从基类再次调用,因为中间类是虚继承,Teacher和Student都不能拥有Person类中的属性和方法
-
如:
Assistant::Assistant(string theName,string classTeaching,string classAttending):Teacher(theName, classTeaching),Student(theName,classAttending),Person(theName)
继承机制构造函数补充: 继承机制中的构造器参数要一致,如:
Person(string theName);
Teacher::Teacher(string theName1,string theClass):Person(theName1)
代码实现
#include <iostream>
#include <string>
using namespace std;
#include <string>
//人类
class Person
{
public:
Person(string theName);//构造函数,theName为类的输入参数
void introduce();
protected:
string name;
};
Person::Person(string theName)//构造函数实现
{
name = theName;
}
void Person::introduce()//introduce()函数实现
{
cout << "大家好,我是" << name << "。\n\n";
}
class Teacher:virtual public Person
{
public:
Teacher(string theName1,string theClass);
void teach();//教书
void introduce();
protected:
string classes;
};
Teacher::Teacher(string theName1,string theClass):Person(theName1)//老师的名字继承于人类中的名字
{
classes = theClass;
}
void Teacher::teach()
{
cout<<"教课啦~ "<< name << " 教 "<< classes << "。\n\n";
}
void Teacher::introduce()
{
cout<<"大家好,我是 "<< name <<" ,我教 "<< classes << "。\n\n";
}
class Student:virtual public Person
{
public:
Student(string theName2,string theClass);
void attendClass();//要上课
void introduce();
protected:
string classes;
};
Student::Student(string theName2,string theClass):Person(theName2)//学生名字继承于人类中的名字
{
classes = theClass;
}
void Student::attendClass()
{
cout<<"上课啦~ "<< name <<"加入"<< classes << "学习。\n\n";
}
void Student::introduce()
{
cout<< "大家好,我是" << name << ",我在" << classes << "学习。\n\n";
}
//助教类既继承于老师类,又继承于学生类
class Assistant:public Teacher,public Student
{
public:
Assistant(string theName,string classTeaching,string classAttending);
void introduce();
};
Assistant::Assistant(string theName,
string classTeaching,
string classAttending)
:
Teacher(theName, classTeaching),
Student(theName,classAttending),
Person(theName)
{
//多继承 助教既继承老师类,又继承学生类
}
void Assistant::introduce()
{
cout << "大家好,我是" << Student::name << ".我教" << Teacher::classes << ",";
cout << "同时我在" << Student::classes << "学习。\n\n";
}
int main()
{
Teacher teacher("Teacher1","Teacher1班啊");
Student student("Student","student班啊");
Assistant assistant("助教小帅","Teacher1班啊","student班啊");
teacher.introduce();
teacher.teach();
student.introduce();
student.attendClass();
assistant.introduce();
assistant.teach();
assistant.attendClass();
return 0;
}