小甲鱼-C++快速入门笔记(29)之多继承

什么时候需要用到多继承呢?

----只要你遇到的问题无法只用一个“是一个”关系来描述的时候,就是多继承出场的时候。

----举个例子:在学校里有老师和学生,他们都是人(Person),我们可以用“老师是人”和“学生是人”语法来描述这种情况。

----从面向对象编程角度上来看,我们应该创建一个名为Person的基类和两个名为Teacher和Student的子类,后两者是从前者继承来的。

问题来了:有一部分学生还教课挣钱(助教),该怎么办?这样就存在了既是老师又是学生的复杂关系,也就是同时存在着两个“是一个”的关系。

我们需要写一个TeachingStudent类让它同时继承Teacher类和Student类,换句话说,就是需要使用多继承。

基本语法:

class TeachingStudent:public Student,public Teacher

{....}

例子:

要求:创建一个由Person, Teacher, Student和TeachingStudent构成的类层次结构.

#include <iostream>
#include <string>

using namespace std;

class Person
{
public:
	Person(string theName);

	void introduce();

protected:
	string name;
};

class Teacher:public Person
{
public:
	Teacher(string theName, string theClass);

	void teach();
	void introduce();

protected:
	string classes;
};

class Student:public Person
{
public:
	Student(string theName, string theClass);

	void attendClass();
	void introduce();

protected:
	string classes;
};

class TeachingStudent:public Student, public Teacher
{
public:
	TeachingStudent(string theName, string classTeaching, string classAttending);

	void introduce();

};

Person::Person(string theName)
{
	name = theName;
}

void Person::introduce()
{
	cout << "大家好,我是" << name << endl;
}

Teacher::Teacher(string theName, string theClass):Person(theName)
{
	classes = theClass;
}

void Teacher::teach()
{
	cout << name << "教" << classes << endl;
}

void Teacher::introduce()
{
	cout << "大家好,我是" << name << ",我教" << classes << endl;
}

Student::Student(string theName, string theClass):Person(theName)
{
	classes = theClass;
}

void Student::attendClass()
{
	cout << name << "加入" << classes << "学习.\n";
}

void Student::introduce()
{
	cout << "大家好,我是" << name << ",我在" << classes << "学习.\n";
}

TeachingStudent::TeachingStudent(string theName,
								 string classTeaching,
								 string classAttending)
								 :Teacher(theName, classTeaching), 
								 Student(theName, classAttending)
{
}

void TeachingStudent::introduce()
{
	cout << "大家好,我是" << Student::name << ",我教" << Teacher::classes << ",";
	cout << "同时我在" << Student::classes << "学习.\n";
}

int main()
{
	Teacher teacher("小甲鱼", "C++入门班");
	Student student("迷途羔羊", "C++入门班");
	TeachingStudent teachingStudent("丁丁", "C++入门班", "C++进阶班");

	teacher.introduce();
	teacher.teach();
	student.introduce();
	student.attendClass();
	teachingStudent.introduce();
	teachingStudent.teach();
	teachingStudent.attendClass();

	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_30708445/article/details/88750571