【问题描述】
采用私有继承完成学生信息类和研究生信息类的设计。
设计学生信息类( Student )和设计研究生信息类( Graduate ),Graduate 类公有继承 Student 类,而 Student 类私有继承 People 类,并实现他们的成员函数以及一个普通函数,具体要求如下:
Graduate 类
增加一个成员变量研究方向:int ResearchID,以及一个成员函数:void PrintResearchID(),函数用来输出 ResearchID 的值,输出格式为:研究方向:ResearchID。
Student 类
补充有成员函数:void PrintSID(),函数输出成员变量 SID 的值,输出格式为:学号:SID。
普通函数:Set(int sid,int rid,string name,Graduate *ptr)函数,它用前三个参数设置 ptr 所指对象的三个成员。
People 基类,它有一个公有成员变量姓名 Name,一个公有成员函数 PrintName(函数的功能是打印出 Name 的值)
【样例输入】
1 304 厉宏富
【样例输出】
学号:1
姓名:厉宏富
研究方向:304
#include<string>
#include<iostream>
using namespace std;
class People
{
public:
string Name;
void PrintName();
};
void People::PrintName()
{
cout << "姓名:" << Name << endl;
}
//私有继承 People 类
class Student :private People
{
public:
int SID;
void PrintSID();
int gSID(int b){SID=b;return SID;}
string gName(string c){Name=c; return Name;}
};
void Student::PrintSID()
{
//输出学号 SID
cout<<"学号:"<<SID<<endl;
}
// 公有继承 Student 类
class Graduate:public Student
{
int ResearchID;
public:
void PrintResearchID();
int gResearchID(int a){ResearchID=a; return ResearchID;}
};
void Graduate::PrintResearchID()
{
//输出研究方向 ResearchID
cout<<"研究方向:"<<ResearchID<<endl;
}
void Set(string name,int sid,int rid,Graduate *ptr)
{
//设置 ptr 所指对象的三个成员
ptr->Graduate::Student::gName(name);
ptr->Graduate::Student::gSID(sid);
ptr->gResearchID(rid);
}
int main()
{
int i,j;
string name;
cin >> i >> j >> name;
Graduate st;
Set(name,i,j,&st);
((Student*)&st)->PrintSID();
((People*)&st)->PrintName();
st.PrintResearchID();
return 0;
}
【注】此分栏为西安理工大学C++练习题,所有答案仅供同学们参考。