在學校里有老師和學生,他們都是人,我么應該創建一個名為 Person 的基類和兩個名為 Teacher 和Student 的子類,后兩者是從前者繼承來的
有一部分學生還教課掙錢(助教),也就是同時存在著兩個”是一個”關系,我們需要寫一個 TeschingStudent 類讓它同時繼承 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<<"Hello,I`m"<<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<<",";std::cout<<"同時我在"<<Student::classes<<"學習。\n\n";
}int main()
{Teacher teacher("小紅","入門班");Student student("蘭蘭","C++入門班");TeachingStudent teachingStudent("茗茗","C++入門班級","C++進階班");teacher.introduce();teacher.teach();student.introduce();student.attendClass();teachingStudent.introduce();teachingStudent.teach();teachingStudent.attendClass();return 0;
}
?
注意:
- 在使用多繼承的時候,一定要特別注意繼承了基類的多少個副本。
- 在使用多繼承的時候,最安全最簡明的做法是從沒有任何屬性且只有抽象方法的類開始繼承。
- 按照上邊這么做可以讓你遠離后代子類可能擁有好幾個基類屬性的問題。
- 這樣的類又叫做接口( interface )。
未完待續。。。?