定义个人类person,其数据成员有姓名 性别 出生年月,并以person类为基类定义一个学生的派生类student,增加描述学生的信息:班级 学号 专业 英语成绩和数学成绩。再由基类person定义一个职工的派生类employee,增加描述职工的信息:部门 职称 工资。编程实现学生与职工的输入与输出
#include <iostream>
#include <string>
using namespace std;
class Person {
protected:
string name;
bool gender;
int birth_year, birth_month;
public:
Person(string _n = "", bool _g = true, int _y = 0, int _m = 0)
: name(_n), gender(_g), birth_year(_y), birth_month(_m) {}
virtual void input() {
cout << "请输入姓名:";
cin >> name;
cout << "请输入性别(0表示女性,1表示男性):";
cin >> gender;
cout << "请输入出生年月(例如:2004 4):";
cin >> birth_year >> birth_month;
}
virtual void output() {
cout << "姓名:" << name << endl;
cout << "性别:" << (gender ? "男" : "女") << endl;
cout << "出生日期:" << birth_year << "年" << birth_month << "月" << endl;
}
};
class Student : public Person {
protected:
string class_name, student_id, major;
float english_score, math_score;
public:
Student(string _cn = "", string _id = "", string _m = "", float _es = 0, float _ms = 0)
: class_name(_cn), student_id(_id), major(_m), english_score(_es), math_score(_ms) {}
void input() {
Person::input();
cout << "请输入班级:";
cin >> class_name;
cout << "请输入学号:";
cin >> student_id;
cout << "请输入专业:";
cin >> major;
cout << "请输入英语成绩:";
cin >> english_score;
cout << "请输入数学成绩:";
cin >> math_score;
}
void output() {
Person::output();
cout << "班级:" << class_name << endl;
cout << "学号:" << student_id << endl;
cout << "专业:" << major << endl;
cout << "英语成绩:" << english_score << endl;
cout << "数学成绩:" << math_score << endl;
}
};
class Employee : public Person {
protected:
string department, title;
float salary;
public:
Employee(string _dep = "", string _t = "", float _s = 0)
: department(_dep), title(_t), salary(_s) {}
void input() {
Person::input();
cout << "请输入部门:";
cin >> department;
cout << "请输入职称:";
cin >> title;
cout << "请输入工资:";
cin >> salary;
}
void output() {
Person::output();
cout << "部门:" << department << endl;
cout << "职称:" << title << endl;
cout << "工资:" << salary << endl;
}
};
int main() {
Person* person;
int type;
cout << "请选择要输入的对象类型(0表示学生,1表示职工):";
cin >> type;
if (type == 0) {
person = new Student;
} else {
person = new Employee;
}
person->input();
person->output();
delete person;
return 0;
}