多继承——C++(29)

多继承

什么时候使用多继承?

  • 当你遇到的问题无法用“是一个”来描述的时候。就需要用到多继承。

比如,当我们定义了一个Person的基类,又创建了一个Teacher和一个Student的子类,但是我们又想描述一个兼职当教师的学生的时候,我们就需要写一个类,命名为TeachingStudent,来同时继承Teacher和Student类,这就是多继承。

基本语法

class TeachingStudent : public Student,public Teacher
{
	...
}

即,在继承第一个的语法上加上逗号,再加上第二个继承的语法。

注意

  • 代码涉及到继承机制中的构造器,注意其声明方式。

代码实现

#include <iostream>
#include <string>

using namespace std;

#include <string>
//人类
class Person
{
public:
    Person(string theName);//构造函数,theName为类的输入参数
    void introduce();
protected:
    string name;
};
Person::Person(string theName)//构造函数实现
{
    name = theName;
}
void Person::introduce()//introduce()函数实现
{
    cout << "大家好,我是" << name << "。\n\n";
}

//老师类继承于人类
class Teacher:public Person
{
public:
    Teacher(string theName,string theClass);

    void teach();//教书
    void introduce();
protected:
    string classes;
};
Teacher::Teacher(string theName,string theClass):Person(theName)//老师的名字继承于人类中的名字
{
    classes = theClass;
}
void Teacher::teach()
{
    cout<<"教课啦~ "<< name << " 教 "<< classes << "。\n\n";
}
void Teacher::introduce()
{
    cout<<"大家好,我是 "<< name <<" ,我教 "<< classes << "。\n\n";
}

//学生类继承于人类
class Student:public Person
{
public:
    Student(string theName,string theClass);

    void attendClass();//要上课
    void introduce();
protected:
    string classes;
};
Student::Student(string theName,string theClass):Person(theName)//学生名字继承于人类中的名字
{
    classes = theClass;
}
void Student::attendClass()
{
    cout<<"上课啦~ "<< name <<"加入"<< classes << "学习。\n\n";
}
void Student::introduce()
{
    cout<< "大家好,我是" << name << ",我在" << classes << "学习。\n\n";
}

//助教类既继承于老师类,又继承于学生类
class Assistant:public Teacher,public Student
{
public:
    Assistant(string theName,string classTeaching,string classAttending);

    void introduce();
};
Assistant::Assistant(string theName,string classTeaching,string classAttending):Teacher(theName, classTeaching),Student(theName,classAttending)
{

//多继承 助教既继承老师类,又继承学生类

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

int main()
{
    Teacher teacher("Teacher","Teacher班啊");
    Student student("Student","Teacher班啊");
    Assistant assistant("助教小帅","另一个班","student班啊");

    teacher.introduce();
    teacher.teach();

    student.introduce();
    student.attendClass();

    assistant.introduce();
    assistant.teach();
    assistant.attendClass();

    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

la via

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值