【问题描述】设计一个用于人事管理的People(人员)类。考虑到通用性,这里只抽象出所有类型人员都具有的属性:姓名char name[11]、编号char number[7]、性别char sex[3]、生日birthday、身份证号char id[19]。其中“出生日期”声明为一个“日期”类内嵌子对象。用成员函数实现对人员信息的录入和显示。要求包括:构造函数和析构函数、拷贝构造函数、内联成员函数。在测试程序中声明people类的对象数组(要求使用动态内存分配生成对象数组),录入数据并显示相关信息。注:输出信息时先通过拷贝构造函数生成第一个员工的副本并输出其相关信息,然后再输出所有员工的相关信息。
时间: 2024-03-24 17:37:28 浏览: 95
好的,我会根据你的要求回答你的问题。
关于人事管理的People类的设计,可以按照如下方式实现。
```cpp
#include <iostream>
#include <cstring>
using namespace std;
// 日期类
class Date {
public:
Date(int year = 1900, int month = 1, int day = 1) {
m_year = year;
m_month = month;
m_day = day;
}
void display() const {
cout << m_year << "-" << m_month << "-" << m_day << endl;
}
private:
int m_year;
int m_month;
int m_day;
};
// 人员类
class People {
public:
People(const char* name = "", const char* number = "", const char* sex = "", const char* id = "", int year = 1900, int month = 1, int day = 1) {
strcpy(m_name, name);
strcpy(m_number, number);
strcpy(m_sex, sex);
strcpy(m_id, id);
m_birthday = new Date(year, month, day);
}
~People() {
delete m_birthday;
}
People(const People& other) {
strcpy(m_name, other.m_name);
strcpy(m_number, other.m_number);
strcpy(m_sex, other.m_sex);
strcpy(m_id, other.m_id);
m_birthday = new Date(*other.m_birthday);
}
void display() const {
cout << "Name: " << m_name << endl;
cout << "Number: " << m_number << endl;
cout << "Sex: " << m_sex << endl;
cout << "Birthday: ";
m_birthday->display();
cout << "ID: " << m_id << endl;
}
private:
char m_name[11];
char m_number[7];
char m_sex[3];
char m_id[19];
Date* m_birthday;
};
int main() {
int n;
cout << "Please enter the number of people: ";
cin >> n;
People* peopleList = new People[n];
for (int i = 0; i < n; i++) {
char name[11], number[7], sex[3], id[19];
int year, month, day;
cout << "Please enter the name of the " << i+1 << "th person: ";
cin >> name;
cout << "Please enter the number of the " << i+1 << "th person: ";
cin >> number;
cout << "Please enter the sex of the " << i+1 << "th person: ";
cin >> sex;
cout << "Please enter the birthday of the " << i+1 << "th person (yyyy-mm-dd): ";
scanf("%d-%d-%d", &year, &month, &day);
cout << "Please enter the ID of the " << i+1 << "th person: ";
cin >> id;
peopleList[i] = People(name, number, sex, id, year, month, day);
}
cout << "The information of the first person is:" << endl;
People firstPerson(peopleList[0]);
firstPerson.display();
cout << "The information of all people are:" << endl;
for (int i = 0; i < n; i++) {
peopleList[i].display();
cout << endl;
}
delete[] peopleList;
return 0;
}
```
在这个实现中,我们定义了一个Date类来处理“出生日期”的信息。在People类中,我们使用了动态内存分配来处理“出生日期”的对象,并在构造函数中进行了初始化。另外,我们还定义了拷贝构造函数来处理对象的复制。在析构函数中,我们需要注意在删除动态分配的对象时需要使用`delete`操作符。
在主函数中,我们首先获取要输入的人数,然后定义了一个People类型的动态数组`peopleList`,并在循环中对每个人员的信息进行输入和存储。为了测试拷贝构造函数,我们将第一个人员的信息先进行拷贝,然后输出第一个人员的信息和所有人员的信息。最后,我们需要在程序结束前释放动态分配的内存。
阅读全文