|

楼主 |
发表于 2015-1-21 21:10:01
|
显示全部楼层
多继承与虚继承
- #include <iostream>
- #include <string>
- class Person
- {
- public:
- Person(std::string theName);
- void introduce();
- protected:
- std::string name;
- };
- class Teacher :virtual public Person
- {
- public:
- Teacher(std::string theName, std::string theClass);
- void teach();
- void introduce();
- protected:
- std::string classes;
- };
- class Student :virtual 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";
- }
- Teacher::Teacher(std::string theName, std::string theClass) :Person(theName)
- {
- classes = theClass;
- }
- void Teacher::teach()
- {
- std::cout << name << "教" << classes << "。\n";
- }
- void Teacher::introduce()
- {
- std::cout << "大家好,我是" << name << ",我教" << classes << "。\n";
- }
- Student::Student(std::string theName, std::string theClass) :Person(theName)
- {
- classes = theClass;
- }
- void Student::attendClass()
- {
- std::cout << name << "加入" << classes << "学习。\n";
- }
- void Student::introduce()
- {
- std::cout << "大家好,我是" << name << ",我在" << classes << "学习。\n";
- }
- TeachingStudent::TeachingStudent(std::string theName,
- std::string classTeaching, std::string classAttending) :Teacher(theName, classTeaching), Student(theName, classAttending),Person(theName)
- {
- }
- void TeachingStudent::introduce()
- {
- std::cout << "大家好,我是" << name << "。我教" << Teacher::classes << ","<<"同时,我在"<<Student::classes<<"学习。\n";
- }
- int main()
- {
- Teacher teacher("天天", "初级语言");
- Student student("小白", "初级语言");
- TeachingStudent teachingstudent("飞鱼", "初级语言", "高级语言");
- teacher.introduce();
- teacher.teach();
- student.introduce();
- student.attendClass();
- teachingstudent.introduce();
- teachingstudent.teach();
- teachingstudent.attendClass();
- return 0;
- }
复制代码 |
|