在此示例中,我们使用了一个 `Employee` 类来表示员工。该类包含了员工的姓名、年龄、地址和薪水等信息,并提供了获取这些信息的成员函数。
在主函数中,我们使用一个指向 `Employee` 类对象的指针数组 `employees` 来存储所有员工的信息。当用户选择添加新员工选项时,我们使用 `new` 运算符动态分配一个新的 `Employee` 对象,并将其添加到 `employees` 数组中。
当用户选择搜索员工选项时,我们遍历 `employees` 数组来查找与用户输入的姓名匹配的员工。如果找到了匹配的员工,我们使用 `Employee` 类的成员函数来获取该员工的信息。如果没有找到匹配的员工,我们向用户显示一条相应的消息。
当用户选择显示所有员工选项时,我们遍历 `employees` 数组并使用 `Employee` 类的成员函数来显示每个员工的信息。
最后,当用户选择退出程序选项时,我们释放所有 `Employee` 对象的内存,并终止程序运行。
需要注意的是,在实际应用中,为了使程序更健壮,我们需要添加输入验证和错误处理功能,例如在用户输入无效数据时向用户显示一条错误消息并要求重新输入。
#include <iostream>
#include <string>
using namespace std;
// 定义员工类
class Employee {
private:
string name;
int age;
string address;
float salary;
public:
// 构造函数
Employee(string n, int a, string addr, float s) {
name = n;
age = a;
address = addr;
salary = s;
}
// 获取员工姓名
string get_name() {
return name;
}
// 获取员工年龄
int get_age() {
return age;
}
// 获取员工地址
string get_address() {
return address;
}
// 获取员工薪水
float get_salary() {
return salary;
}
};
int main() {
int option, i, n = 0;
Employee* employees[100];
string search_name;
do {
// 显示菜单选项
cout << endl << "Employee Management System" << endl;
cout << "---------------------------" << endl;
cout << "1. Add new employee" << endl;
cout << "2. Search employee" << endl;
cout << "3. Display all employees" << endl;
cout << "4. Exit" << endl;
cout << "Enter your choice: ";
cin >> option;
switch (option) {
case 1:
// 添加新员工
string name, address;
int age;
float salary;
cout << endl << "Enter employee name: ";
cin >> name;
cout << "Enter employee age: ";
cin >> age;
cout << "Enter employee address: ";
cin >> address;
cout << "Enter employee salary: ";
cin >> salary;
employees[n] = new Employee(name, age, address, salary);
n++;
break;
case 2:
// 搜索员工
bool found = false;
cout << endl << "Enter employee name to search: ";
cin >> search_name;
for (i = 0; i < n; i++) {
if (search_name == employees[i]->get_name()) {
cout << "Name: " << employees[i]->get_name() << endl;
cout << "Age: " << employees[i]->get_age() << endl;
cout << "Address: " << employees[i]->get_address() << endl;
cout << "Salary: " << employees[i]->get_salary() << endl;
found = true;
break;
}
}
if (!found) {
cout << "Employee not found." << endl;
}
break;
case 3:
// 显示所有员工
cout << endl << "All employees:" << endl;
for (i = 0; i < n; i++) {
cout << endl << "Employee " << i + 1 << ":" << endl;
cout << "Name: " << employees[i]->get_name() << endl;
cout << "Age: " << employees[i]->get_age() << endl;
cout << "Address: " << employees[i]->get_address() << endl;
cout << "Salary: " << employees[i]->get_salary() << endl;
}
break;
case 4:
// 退出程序
cout << endl << "Exiting program..." << endl;
break;
default:
// 无效选项
cout << endl << "Invalid option. Please try again." << endl;
}
} while (option != 4);
// 释放员工对象内存
for (i = 0; i < n; i++) {
delete employees[i];
}
return 0;
}