设计职员类,它继承了Person类并组合了Date类。C++
时间: 2024-02-16 08:59:55 浏览: 29
好的,以下是职员类的C++实现:
```cpp
#include <iostream>
#include <string>
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 print() {
cout << year << "-" << month << "-" << day << endl;
}
};
class Person {
private:
string name;
int age;
public:
Person(string n, int a) {
name = n;
age = a;
}
void print() {
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
}
};
class Staff : public Person {
private:
Date hireDate;
public:
Staff(string n, int a, int y, int m, int d) : Person(n, a), hireDate(y, m, d) {}
void print() {
Person::print();
cout << "入职日期:";
hireDate.print();
}
};
int main() {
Staff s("张三", 28, 2021, 8, 1);
s.print();
return 0;
}
```
这里我们使用了三个类:Person类表示人员,Date类表示日期,Staff类表示职员。Staff类继承了Person类,组合了Date类。
在Staff类的构造函数中,我们通过Person类的构造函数初始化了姓名和年龄,通过Date类的构造函数初始化了入职日期。print()函数中,我们先调用Person类的print()函数输出姓名和年龄,然后输出入职日期。
最后在main()函数中创建了一个Staff对象s,并调用了它的print()函数。输出结果为:
```
姓名:张三
年龄:28
入职日期:2021-8-1
```