C++第5次实验—多继承

一、问题及代码


<span style="font-size:12px;">/* 
* 文件名称:Ex5-2.cpp 
* 完成日期:2016 年 5 月 6 日 
* 版 本 号:v1.0 
* 对任务及求解方法的描述部分:
* 分别定义Teacher(教师)类和Cadre(干部)类,采用多重继承方式由这两个类派生出新类Teacher_Cadre(教师兼干部)。
* 输入描述:无 
* 问题描述: 要求: 
*(1)在两个基类中都包含姓名、年龄、性别等数据成员。 
*(2)在Teacher类中还包含数据成员title(职称),在Cadre类中还包含数据成员post(职务),在Teacher_Cadre类中还包含数据成员wages(工资)。 
*(3)对两个基类中的姓名、年龄、性别等数据成员用相同的名字,在引用这些数据成员时,指定作用域。 
*(4)在类体中声明成员函数,在类外定义成员函数。 
*(5)在派生类Teacher_Cadre的成员函数show中调用Teacher类中的display函数,输出姓名、年龄、性别、职称,然后再用cout语句输出职务与工资。
* 程序输出:略
* 问题分析:略
* 算法设计:略 
*/
#include <iostream>
#include <string>
using namespace std;

class Teacher
{
	public:
    string name,sex;
    int age;
    string title;//职称

    Teacher(string,string,int,string);
    void display();
};
Teacher::Teacher(string n,string s,int a,string t)
{
    name=n;sex=s;age=a;title=t;
}
void Teacher::display()
{
    cout<<"姓名:"<<name<<endl;
    cout<<"年龄:"<<age<<endl;
    cout<<"性别:"<<sex<<endl;
    cout<<"职称:"<<title<<endl;
}
class Cadre
{
public:
    string name,sex;
    int age;
    string post;//职务
    Cadre(string,string,int,string);
};
Cadre::Cadre(string n,string s,int a,string p)
{
    name=n;sex=s;age=a;post=p;
}
class Teacher_Cadre:public Teacher, public Cadre
{
    double wages;
public:
    Teacher_Cadre(string,string,int,string,string,double);
    void show();
};
Teacher_Cadre::Teacher_Cadre(string n,string s,int a,string t,string p,double w):Teacher(n,s,a,t),Cadre(n,s,a,p),wages(w){}

void Teacher_Cadre::show()
{
    display();
    cout<<"职务:"<<post<<endl;
    cout<<"工资:"<<wages<<endl;
}
int main()
{
    Teacher_Cadre t1("曾辉","男",42,"副教授","主任",1534.5);
    t1.show();
    return 0;
}</span>


二、运行结果



三、知识点总结

派生类:class 类名 :继承方式 基类1,继承方式 基类2 ......{};

派生类构造函数: 派生类名::派生类名(总参数表):基类1(参数表),基类2(参数表)......{新增成员的初始化;}

指定作用域访问成员:对象.基类1::a;    对象.基类2::a;


四、感悟与心得


多看,多记,多用。

猜你喜欢

转载自blog.csdn.net/ecjtusanhu/article/details/51330109