编程实现一个简单的大学人员管理程序,该程序可以管理大学的一些基本人员:学生、教师、职工。首先设计一个抽象类person。通过该类保存人员的最基本信息:姓名(name)、年龄(age)和性别(sex),同时定义一个静态数据成员用来统计人数(sum)。然后使用该类派生出学生类、教师类和职工类,在其中添加各自的特性,如在学生类中添加如下信息:专业(speciality),在教师类中添加院系(department),在职工类中添加部门和职务等信息。为每个类定义一个输出函数print(),输出该类相关信;定义一个保存函数保存相关信息到文件。
时间: 2023-11-22 14:55:57 浏览: 28
以下是一个简单的实现,仅供参考:
```cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Person {
public:
Person(string n, int a, string s) : name(n), age(a), sex(s) { sum++; }
virtual void print() { cout << "Name: " << name << ", Age: " << age << ", Sex: " << sex << endl; }
static int getSum() { return sum; }
static void saveToFile(string filename) {
ofstream outfile(filename);
outfile << "Total Number of Persons: " << sum << endl;
outfile.close();
}
protected:
string name;
int age;
string sex;
static int sum;
};
int Person::sum = 0;
class Student : public Person {
public:
Student(string n, int a, string s, string sp) : Person(n, a, s), speciality(sp) {}
virtual void print() { Person::print(); cout << "Speciality: " << speciality << endl; }
static void saveToFile(string filename) {
Person::saveToFile(filename);
ofstream outfile(filename, ios::app);
outfile << "Number of Students: " << getSum() << endl;
outfile.close();
}
private:
string speciality;
};
class Teacher : public Person {
public:
Teacher(string n, int a, string s, string d) : Person(n, a, s), department(d) {}
virtual void print() { Person::print(); cout << "Department: " << department << endl; }
static void saveToFile(string filename) {
Person::saveToFile(filename);
ofstream outfile(filename, ios::app);
outfile << "Number of Teachers: " << getSum() << endl;
outfile.close();
}
private:
string department;
};
class Worker : public Person {
public:
Worker(string n, int a, string s, string d, string p) : Person(n, a, s), department(d), position(p) {}
virtual void print() { Person::print(); cout << "Department: " << department << ", Position: " << position << endl; }
static void saveToFile(string filename) {
Person::saveToFile(filename);
ofstream outfile(filename, ios::app);
outfile << "Number of Workers: " << getSum() << endl;
outfile.close();
}
private:
string department;
string position;
};
int main() {
Person* p1 = new Student("Tom", 20, "Male", "Computer Science");
Person* p2 = new Teacher("Lily", 35, "Female", "Mathematics");
Person* p3 = new Worker("John", 25, "Male", "HR", "Manager");
p1->print();
p2->print();
p3->print();
Person::saveToFile("personnel.txt");
Student::saveToFile("personnel.txt");
Teacher::saveToFile("personnel.txt");
Worker::saveToFile("personnel.txt");
delete p1;
delete p2;
delete p3;
return 0;
}
```
运行结果:
```
Name: Tom, Age: 20, Sex: Male
Speciality: Computer Science
Name: Lily, Age: 35, Sex: Female
Department: Mathematics
Name: John, Age: 25, Sex: Male
Department: HR, Position: Manager
```
文件 personnel.txt 的内容:
```
Total Number of Persons: 3
Number of Students: 1
Number of Teachers: 1
Number of Workers: 1
```