Person类、学生类、教师类和研究生类(多重继承)
【问题描述】
研究生Graduate既有学生Student的属性,又有教师Teacher的属性,通过多重继承说明一个研究生类Graduate。
从前面实验题目完成的Person类派生出Teacher类,新增专业(dept)和月薪(salary)属性,并定义Teacher类的构造函数初始化新增的数据成员,showMe成员函数显示新增的数据成员的值。
再从Person类派生出Student类,新增班级(class)和学号(ID)属性,定义Student类的构造函数初始化新增的数据成员,showMe成员函数显示新增的数据成员的值。
通过“多重继承”说明一个研究生类Graduate,定义Graduate类的构造函数,定义Graduate类的showMe成员函数显示各个数据成员的值。
主函数设计如下,请勿修改:
int main(){
Graduate stu1("Lisi",22,'m',"College of Informatics",2000,"2015013","S101");
stu1.showMe();
return 0;
}
提示:
(1)Graduate的父类是Student和Teacher,
而Student和Teacher有共同的父类Person,
如果是普通继承则姓名、性别和年龄就发生了重复。因此,这一题需要用到虚基类的概念。
(2)注意showMe()成员函数在每个类里都有。
【样例输出】
class: S101
id: 2015013
name: Lisi
sex: m
age: 22
co: College of Informatics
salary: 2000
#include <iostream>
#include <string.h>
using namespace std;
//Person基类
class Person{
char name[10];
int age;
char sex;
public:
void Register(char *s,int n,char c)
{
int len = strlen(s);
int i;
for(i=0;i<len;++i)
name[i] = s[i];
name[i] = '\0';
age=n;
sex=(c=='m'?0:1);
}
char *getName() { return name; }
char getSex() { return sex==0?'m':'f'; }
int getAge() { return age; }
void showMe() { cout<<"name: "<<getName()<<endl<<"sex: "<<getSex()<<endl<<"age: "<<getAge()<<endl; }
};
//Teacher派生类(虚基类)
class Teacher : virtual public Person
{
private:
char * dept;
int salary;
public:
Teacher( char *n, int a, char c, const char *d, int s ) : salary(s)
{
Register(n,a,c);
int len = strlen(d);
dept = new char[len+1];
strcpy(dept,d);
}
~Teacher() {delete [] dept;}
void showMe() { cout<<"co: "<<dept<<endl<<"salary: "<<salary<<endl; }
};
//Student派生类(虚基类)
class Student : virtual public Person
{
private:
char * ID;
char * Class;
public:
Student( char *n, int a, char c, const char *id, const char *cla )
{
Register(n,a,c);
int len1 = strlen(id);
ID = new char[len1+1];
strcpy(ID,id);
int len2 = strlen(cla);
Class = new char[len2+1];
strcpy(Class,cla);
}
~Student() {delete [] ID; delete [] Class; }
void showMe() { cout<<"class: "<<Class<<endl<<"id: "<<ID<<endl; }
};
//Graduate派生类(多重继承)
class Graduate : public Teacher, public Student
{
public:
Graduate(char *n, int a, char c, const char *d, int s, const char *id, const char *cla )
: Teacher(n,a,c,d,s), Student(n,a,c,id,cla)
{
Register(n,a,c);
}
void showMe()
{
Student::showMe();
Person::showMe();
Teacher::showMe();
}
};
int main()
{
Graduate stu1("Lisi",22,'m',"College of Informatics",2000,"2015013","S101");
stu1.showMe();
return 0;
}