代码实现定义一个学生类(Student):保护成员-->姓名、年龄、成绩以及相关函数定义一个老师类(Teacher):保护成员-->年龄、职称以及相关函数 、输出函数由学生类和老师类共同派生出研
#include <iostream>
#include <cstring>
using namespace std;
//定义学生类
class Stdent
{
protected:
string name;
int age;
double score;
public:
Stdent():name(NULL),age(0),score(0){cout<<"无参构造\n"<<endl;} //无参构造初始化
Stdent(const string n,const int a,const double s):name(n),age(a),score(s)
{
cout<<"Stdent::有参构造"<<endl;
}
~Stdent()
{
cout<<"Stdent::析构函数"<<endl;
}
};
//定义老师类
class Teacher
{
protected:
int age;
string subject;
public:
Teacher():age(0),subject("Chinese"){cout<<"Teacher::无参构造"<<endl;}
Teacher(const int a,const string s):age(a),subject(s)
{
cout<<"Teacher::有参构造"<<endl;
}
~Teacher()
{
cout<<"Teacher::析构函数"<<endl;
}
};
//定义研究生类
class Graduate:public Stdent,public Teacher
{
public:
char sex; //性别:Y男 X女
Graduate():sex('Y'){}
Graduate(string n,int a1,double s1,int a2,string s2,int x):Stdent(n,a1,s1),Teacher(a1,s2),sex(x){}
void show()
{
cout<<"name="<<name<<endl;
cout<<"age="<<Stdent::age<<endl;
cout<<"score="<<score<<endl;
cout<<"subject="<<subject<<endl;
cout<<"sex="<<sex<<endl;
}
};
int main()
{
cout<<"第四个参为哑元,可随便填整数"<<endl;
Graduate str("zhangsan",18,99,20,"English",'Y'); //第四个参为哑元,可随便填整数
cout<<"性别:Y男 X女"<<endl;
str.show();
return 0;
}