首页 > 学院 > 开发设计 > 正文

虚函数与继承

2019-11-06 07:08:13
字体:
来源:转载
供稿:网友

学生类,派生出文科生类和理科生类,它们继承了学生类的一些基本信息如姓名、学号、性别,又有着自身的成员,比如说文科类有政治、历史地理科目、理科类有化学、物理、生物科目。在录入学生信息时既要录入他们的基本信息,又要录入他们各科的成绩,所以就派生出文科类和理科类,同时对派生出来的类中的一些函数进行覆盖

#include<iostream>#include<list>using namespace std;class Stud{//基类:学生类 public: string name; int nNum; char cSex; virtual void PRint() const { cout << "姓名:" << name << " 学号:" << nNum << " 性别:" << cSex << endl; } virtual void Input() { cout << "请输入学生的姓名、学号、性别:"; cin >> name >> nNum >> cSex; } virtual~Stud() { }};list<Stud*> g_list;class ScienceStud : public Stud{//理科类 public: void Input() override { Stud::Input(); cout << "请输入学生的化学、物理、生物成绩:" << endl; cin >> fChemistry >> fPhysics >> fBiology; } void Print() const override { Stud::Print(); cout << "化学:" << fChemistry << "物理:" << fPhysics << "生物:" << fBiology << endl; } private: float fChemistry; float fPhysics; float fBiology;} ;class LiberalStud : public Stud{//文科类 public: void Input() override { Stud::Input(); cout << "请输入学生的政治、历史、地理成绩:" << endl; cin >> fPolitics >> fHistory >> fGeography; } void Print() const override //override 派生类函数与基类函数名和参数都相同 { //需要进行覆盖 overwrite 函数名相同但参数或类型不同的重写 Stud::Print(); cout << "政治:" << fPolitics << "历史:" << fHistory << "地理:" << fGeography << endl; } private: float fPolitics; float fHistory; float fGeography;};void Input(){ cout << "选择文科或理科:" ; int i = 0; Stud *p = NULL; cin >> i; switch(i) { case 1: p = new ScienceStud; break; case 2: p = new LiberalStud; break; } if(p) {//输入信息 p->Input(); p->Print(); } g_list.push_back(p); }void Print(){ list<Stud*>::iterator it = g_list.begin(); while(it != g_list.end()) { Stud *p = *it++; p->Print(); } }int Menu() { cout << "1、浏览信息" << endl; cout << "2、添加信息" << endl; cout << "0、退出" << endl; int i; cin >> i; switch(i) { case 0: return 0; break; case 1: Print(); break; case 2: Input(); break; default: break; } return i;} int main(){ while(Menu()) ; return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表