小甲鱼-C++快速入门笔记(29)之多继承
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了小甲鱼-C++快速入门笔记(29)之多继承,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2579字,纯文字阅读大概需要4分钟。
内容图文
什么时候需要用到多继承呢?
----只要你遇到的问题无法只用一个“是一个”关系来描述的时候,就是多继承出场的时候。
----举个例子:在学校里有老师和学生,他们都是人(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;
}
内容总结
以上是互联网集市为您收集整理的小甲鱼-C++快速入门笔记(29)之多继承全部内容,希望文章能够帮你解决小甲鱼-C++快速入门笔记(29)之多继承所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。