给出下面的一个基类框架:class Person protected int no;编号 public virtual void display输出相关信息 以Person为基类构建出Student、Teacher两个类。生成上述类并编写主函数要求主函数中有一个基类Person的一维数组用于存放学生或教师对象数组长度为10。 主函数根据
#include
class Person { protected: int no; // 编号 public: Person(int no = 0) : no(no) {} virtual ~Person() {} virtual void display() {} };
class Student : public Person { private: int score[5]; // 期末成绩 public: Student(int no = 0) : Person(no) {} ~Student() {} void setScore() { for (int i = 0; i < 5; i++) cin >> score[i]; } virtual void display() { int cnt = 0, sum = 0; for (int i = 0; i < 5; i++) { if (score[i] != -1) { cnt++; sum += score[i]; } } cout << no << " " << 5 - cnt << " "; if (cnt == 0) cout << endl; else cout << sum / cnt << endl; } };
class Teacher : public Person { private: int paper[3]; // 论文数 public: Teacher(int no = 0) : Person(no) {} ~Teacher() {} void setPaper() { for (int i = 0; i < 3; i++) cin >> paper[i]; } virtual void display() { int sum = 0; for (int i = 0; i < 3; i++) sum += paper[i]; cout << no << " " << sum << endl; } };
int main() { Person* p[10]; int i = 0, type, no; while (cin >> type && type != 0) { cin >> no; if (type == 1) { p[i] = new Student(no); ((Student*)p[i])->setScore(); } else { p[i] = new Teacher(no); ((Teacher*)p[i])->setPaper(); } i++; } for (int j = 0; j < i; j++) p[j]->display(); for (int j = 0; j < i; j++) delete p[j]; return 0;
原文地址: https://www.cveoy.top/t/topic/eBUK 著作权归作者所有。请勿转载和采集!