问题描述:设计抽象类Person,派生出具体类:学生类Student和教师类Teacher,创建若干不同类对象后并在主方法中测试。
数据成员定义:
Person [ID,姓名,生日]
Student [专业,成绩]
Teacher [职称,工资]
带参构造方法分别为:
Person(int id,String name, int bir)
Student(int id,String name, int bir, String major,double score)
Teacher(int id,String name, int bir, String title, double salary)
toString方法(Eclipse自动生成)
输入格式:第一行整数n表示有n个对象,每个对象占2行,第一行为数字0(表示学生)或1(表示教师),第二行为生成对象的参数。
输出格式:按行输出具体对象的信息。
#include<iostream>
#include<iomanip>
using namespace std;
class Person{
public:
int ID; string Name; int Birthday;
void Set(int id, string name, int birthday){ID=id;Name=name;Birthday=birthday;}
void Print();
};
class Student : public Person{
public:
string Major; double Score;
void Set(int id, string name, int birthday, string major, double score){Person::Set(id,name,birthday);Major=major;Score=score;}
void Print(){cout<<"Student [";Person::Print();cout<<"major="<<Major<<", score="<<fixed<<setprecision(1)<<Score<<"]"<<endl;}
};
Student *per[10];
class Teacher : public Person{
public:
string Title; double Salary;
void Set(int id, string name, int birthday, string title, double salary){Person::Set(id,name,birthday);Title=title;Salary=salary;}
void Print(){cout<<"Teacher [";Person::Print();cout<<"title="<<Title<<", salary="<<fixed<<setprecision(1)<<Salary<<"]"<<endl;}
};
Teacher *perr[10];
void Person::Print(){cout<<"id="<<ID<<", name="<<Name<<", bir="<<Birthday<<", ";}
int main(){
Student *stu; Teacher *tea;
int n, i, choice;
cin>>n;
for(i=0;i<n;i++){
cin>>choice;
if(choice==0){
stu=new Student();
cin>>stu->ID>>stu->Name>>stu->Birthday>>stu->Major>>stu->Score;
per[i]=stu;}
if(choice==1){
tea=new Teacher();
cin>>tea->ID>>tea->Name>>tea->Birthday>>tea->Title>>tea->Salary;
perr[i]=tea;}
}
for(i=0;i<n;i++){
if(per[i]){per[i]->Print();}
else{perr[i]->Print();}}
return 0;
}