多继承(multiple inheritance)可是是面向对象编程技术中心最惹人争议的功能了。
这个概念乍看起来很简单,但它可能引起一些难以预料的后果。
因此,java和c#等面向对象编程语言大都只支持多继承的最简单的版本。
什么时候需要用到多继承?
- 只要你遇到的问题无法只用一个“是一个”关系来描述的时候,就是多继承出场的时候
- 举个例子:在学校里有老师和学生,他们都是人(Person),我们可以用“老师是人”和“学生是人”语法来描述这种情况。
- 从面向对象编程角度上来看,我们应该创建一个名为Person的基类和两个名为Teacher和Student的子类,后两者是从前面继承来的。
问题来了:有一些学生还教课挣钱(助教),这样就存在了既是老师又是学生的复杂关系,也就是同时存在着两个“是一个”关系
我们需要些一个TeachingStudent类让它同时继承Teacher和Student类,换句话说,就是需要使用多继承。
基本语法
class TeachingStudent : public Student, public Teacher
{
}
例子
要求:创建一个由Person,Teacher,Student和TeachingStudent构成的类层次结构。
#include <iostream>
#include <string>
class Person
{
public:
Person(std::string theName);
void introduce();
protected:
std::string name;
};
class Teacher : public Person
{
public:
Teacher(std::string theName, std::string theClass);
void teach();
void introduce();
protected:
std::string classes;
};
class Student : public Person
{
public:
Student(std::string theName, std::string thcClass);
void attendClass();
void introduce();
protected:
std::string classes;
};
class TeachingStudent : public Student, public Teacher
{
public:
TeachingStudent(std::string theName, std::string classTeaching, std::string classAttending);
void introduce();
};
Person::Person(std::string theName)
{
name = theName;
}
void Person::introduce()
{
std::cout << "大家好,我是" << name << std::endl;
}
Teacher::Teacher(std::string theName, std::string theClass) : Person(theName)
{
classes = theClass;
}
void Teacher::introduce()
{
std::cout << "大家好,我是" << name << std::endl;
}
void Teacher::teach()
{
std::cout << name << "教" << classes << "。" << std::endl;
}
Student::Student(std::string theName, std::string theClass) : Person(theName)
{
classes = theClass;
}
void Student::attendClass()
{
std::cout << name << "加入" << classes << "学习" << std::endl;
}
void Student::introduce()
{
std::cout << "大家好,我是" << name << ",我在" << classes << "学习。" << std::endl;
}
TeachingStudent::TeachingStudent(std::string theName, std::string classTeaching, std::string classAttending) : Teacher(theName, classTeaching), Student(theName, classAttending)
{
}
//void TeachingStudent::introduce() //试了一下,两个输出是一样的,我就是试一下,无聊
//{
// std::cout << "大家好,我是" << Student::name << ",我教" << Teacher::classes << ",";
// std::cout << "同时我在" << Student::classes << "学习。" << std::endl;
//}
void TeachingStudent::introduce()
{
std::cout << "大家好,我是" << Teacher::name << ",我教" << Teacher::classes << ",";
std::cout << "同时我在" << Student::classes << "学习。" << std::endl;
}
int main()
{
Teacher teacher("小甲鱼", "C++入门班");
Student student("迷途羔羊", "C++入门班");
TeachingStudent teachingStudent("丁丁", "C++入门班", "C++进阶版");
teacher.introduce();
teacher.teach();
student.introduce();
student.attendClass();
teachingStudent.introduce();
teachingStudent.attendClass();
teachingStudent.teach();
return 0;
}