多继承
什么时候使用多继承?
- 当你遇到的问题无法用“是一个”来描述的时候。就需要用到多继承。
比如,当我们定义了一个Person的基类,又创建了一个Teacher和一个Student的子类,但是我们又想描述一个兼职当教师的学生的时候,我们就需要写一个类,命名为TeachingStudent,来同时继承Teacher和Student类,这就是多继承。
基本语法
class TeachingStudent : public Student,public Teacher
{
...
}
即,在继承第一个的语法上加上逗号,再加上第二个继承的语法。
注意
- 代码涉及到继承机制中的构造器,注意其声明方式。
代码实现
#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:public Person
{
public:
Teacher(string theName,string theClass);
void teach();//教书
void introduce();
protected:
string classes;
};
Teacher::Teacher(string theName,string theClass):Person(theName)//老师的名字继承于人类中的名字
{
classes = theClass;
}
void Teacher::teach()
{
cout<<"教课啦~ "<< name << " 教 "<< classes << "。\n\n";
}
void Teacher::introduce()
{
cout<<"大家好,我是 "<< name <<" ,我教 "<< classes << "。\n\n";
}
//学生类继承于人类
class Student:public Person
{
public:
Student(string theName,string theClass);
void attendClass();//要上课
void introduce();
protected:
string classes;
};
Student::Student(string theName,string theClass):Person(theName)//学生名字继承于人类中的名字
{
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)
{
//多继承 助教既继承老师类,又继承学生类
}
void Assistant::introduce()
{
cout << "大家好,我是" << Student::name << ".我教" << Teacher::classes << ",";
cout << "同时我在" << Student::classes << "学习。\n\n";
}
int main()
{
Teacher teacher("Teacher","Teacher班啊");
Student student("Student","Teacher班啊");
Assistant assistant("助教小帅","另一个班","student班啊");
teacher.introduce();
teacher.teach();
student.introduce();
student.attendClass();
assistant.introduce();
assistant.teach();
assistant.attendClass();
return 0;
}