一、多继承
①基本概念
>>> 多继承(multiple inheritance) 可能是面向对象编程技术中最惹人争议的功能了。
>>> 这个概念咋看起来很简单,但它可能引起一些难以预料的后果。
>>> 因此,JAVA和C#等面向对应编程语言大都至支持多继承的最简单的版本。
单继承:小甲鱼有一个儿子,小甲鱼百年以后,儿子直接继承
多继承:小甲鱼有个一干女儿,但是这个干女儿有很多个干爹,这样整个干女儿会有很多个继承,导致多继承
②什么时候需要用到多继承
》》》只要你遇到的问题无法只用一个“是一个”关系来描述的时候,就是多继承出场的时候。
------举个栗子:在学校里有老师和学生‘他们都是人’(Person‘),我们可以用“老师是人”和“学生是人”语法来描述这种情况。
------从面向对象编程角度上来看,我们应该创建一个名为Person的基类和两个名为Teacher和Student的子类,后两者是从前者继承的。
问题来了:有一部分学生还教课挣钱(助教),该怎么办?酱紫就存在了既是老师又是学生的复杂关系,也就是同时存在这两个“是一个”的关系。
------我们需要写一个TeschingStudent类让它同时继承Teacher类和Student类,换句话说“就是需要使用多继承”。
③如下代码示例:
#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 theClass);
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<<"hello everyone my name is "<< name << "\n";
}
Teacher::Teacher(std::string theName,std::string theClass) : Person(theName)
{
classes = theClass;
}
void Teacher::teach()
{
std::cout<< name << "teach" << classes <<"\n";
}
void Teacher::introduce()
{
std::cout<<"hello everyone my name is "<< name << "teach" << classes << "\n";
}
Student::Student(std::string theName,std::string theClass) : Person(theName)
{
classes = theClass;
}
void Student::attendClass()
{
std::cout<< name << "attend" << classes <<"\n";
}
void Student::introduce()
{
std::cout<<"hello everyone my name is "<< name << "study" << classes << "\n";
}
TeachingStudent::TeachingStudent(std::string theName,std::string ClassTeaching,std::string ClassAttending):Teacher(theName,ClassTeaching),Student(theName,ClassAttending)
{
}
void TeachingStudent::introduce()
{
std::cout<< Student::name << "teach" << Teacher::classes <<"\n";
std::cout<<"at the same time I am study "<<Student:: classes << "\n";
}
int main()
{
Teacher teacher("tom","c++first");
Student student("jery","c++first");
TeachingStudent teachingstudent("three","c++first","c++second");
teacher.introduce();
teacher.teach();
student.introduce();
student.attendClass();
teachingstudent.introduce();
teachingstudent.teach();
teachingstudent.attendClass();
return 0;
}