1. 程式人生 > >C++快速入門---多繼承(20)

C++快速入門---多繼承(20)

C++快速入門---多繼承(20)

 

只要你遇到的問題無法只用一個“是一個”關係來描述的時候,就是多繼承出場的時候。

 

例子:

有一部分學生還教課掙錢(助教),這樣就存在了即是老師又是學生的複雜關係,也就是同時存在著兩個“是一個”關係。

我們需要寫一個TeachingStudent類讓它同時繼承Teacher類和Student類,換句話說,就是需要使用多繼承。

基本語法:

class TeachingStudent : public Student, public Teacher

{...}

 

程式碼如下:

#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 << "大家好,我是" << name << ".\n\n";
}

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

void Teacher::teach()
{
	std::cout << name << "教" << classes << ".\n\n";
}

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

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

void Student::attendClass()
{
	std::cout << name << "加入" << classes << "學習.\n\n";
}

void Student::introduce()
{
	std::cout << "大家好,我是" << name << ",我在" << classes << "學習.\n\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 << ".我教" << Teacher::classes << ",";
}

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;
}