2、设计职员类它继承了Person类并组合了Date类。编写主程序显示职员数据如下:姓名:杨萍出生日期: 1988106性别:女工作部门:团委职务:团委书记工资:6000要求:画出类之间的继承关系图;写出类的设计思路;完整c++代码。
类的继承关系图如下:
+--------+
| Person |
+--------+
|
|
v
+--------+
| Date |
+--------+
|
|
v
+---------------+
| Employee |
+---------------+
| -department |
| -position |
| -salary |
+---------------+
类的设计思路:
- Person类:包含姓名、出生日期、性别三个基本属性。其中出生日期通过组合Date类来实现。
- Date类:包含年、月、日三个属性,通过构造函数初始化。
- Employee类:继承了Person类,并添加了工作部门、职务、工资三个属性,使用private修饰,避免直接访问。对应的set和get函数用public修饰,方便外界操作。
完整c++代码如下:
#include <iostream>
using namespace std;
class Date {
private:
int year;
int month;
int day;
public:
Date(int y, int m, int d) {
year = y;
month = m;
day = d;
}
void setDate(int y, int m, int d) {
year = y;
month = m;
day = d;
}
void showDate() {
cout << year << "." << month << "." << day << endl;
}
};
class Person {
private:
string name;
Date birthdate;
char sex;
public:
Person(string n, Date b, char s) {
name = n;
birthdate = b;
sex = s;
}
void setName(string n) {
name = n;
}
void setBirthdate(Date b) {
birthdate = b;
}
void setSex(char s) {
sex = s;
}
string getName() {
return name;
}
Date getBirthdate() {
return birthdate;
}
char getSex() {
return sex;
}
};
class Employee : public Person {
private:
string department;
string position;
double salary;
public:
Employee(string n, Date b, char s, string d, string p, double sal) : Person(n, b, s) {
department = d;
position = p;
salary = sal;
}
void setDepartment(string d) {
department = d;
}
void setPosition(string p) {
position = p;
}
void setSalary(double sal) {
salary = sal;
}
string getDepartment() {
return department;
}
string getPosition() {
return position;
}
double getSalary() {
return salary;
}
void showEmployee() {
cout << "姓名:" << getName() << endl;
cout << "出生日期:";
getBirthdate().showDate();
cout << "性别:" << getSex() << endl;
cout << "工作部门:" << department << endl;
cout << "职务:" << position << endl;
cout << "工资:" << salary << endl;
}
};
int main() {
Date birth(1988, 10, 6);
Employee emp("杨萍", birth, '女', "团委", "团委书记", 6000);
emp.showEmployee();
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/dpZs 著作权归作者所有。请勿转载和采集!