current position:Home>C++ implements a staff management system based on polymorphism (with source code)

C++ implements a staff management system based on polymorphism (with source code)

2022-06-24 09:15:33loveCC_ orange

In order to find an internship , To learn the Python, Brushed 50 or 60 algorithm problems , Then I began to submit my resume for interview , The result is a round of tours of major factories , want Python The number of development posts is poor . Fortunately, Huawei passed the internship interview ~

I thought I could wait and take it offer 了 , As a result, the bubble pool failed , Huawei's this year RAN Research Department offer Quantity reduction , Because it is not in the top four , So I was pass It fell off . And then I started looking for internships again . After hitting the wall countless times , I feel that I have little talent and learning , There is still too little to learn . So continue to brush questions , Start learning at the same time C++, Ready to C/C++ On the road of development !

From the end of May to now , Basically put C++ I have learned the basic grammar and basic characteristics of , As the end of this phase ,B The online course of the black horse programmer at the station specially wrote this employee management system based on polymorphism to apply these learned features , Today, I will review this project again in this blog post , Sort it out again , Deepen the impression .

Staff management system

Manage system requirements

Employee management system can be used to manage the information of all employees in the company , This tutorial mainly uses C++ To achieve a staff management system based on polymorphism

  • There are three types of employees in the company : Ordinary employees 、 Manager and boss
  • When information is displayed , Need to show employee number 、 Employee's name 、 Positions and responsibilities of employees
  • Responsibilities of ordinary employees : Complete the tasks assigned by the boss , And issue tasks to employees
  • Boss responsibilities : Manage all the affairs of the company

The functions to be implemented in the management system are as follows :

  • Exit management program : Exit the current management program
  • Add employee information : Realize the function of batch adding employees , Enter information into a file , Employee information is : Employee number , Name and department number
  • Display employee information : Show the information of all employees in the company
  • Delete the resigned employee : Delete the designated employee by number
  • Modify employee information : Modify employee's personal information according to the number
  • Find employee information : Search relevant personnel information according to the number or name of the employee
  • Sort by number : According to the employee number , Sort , The collation is specified by the user
  • Empty all documents : Clear all employee information recorded in the file ( Reconfirmation is required before emptying , Prevent false deletion )

Main idea :

Encapsulate the functions of the employee management system into functions , Call when using .

#include<iostream>
using namespace std;
#include"Worker_Manager.h"
#include"employee.h"
#include"Worker.h"
#include"manager.h"
#include"boss.h"

int main()
{
    
	/* //  Test code  Worker* worker = NULL; worker = new Employee(1, " Zhang San ", 1); worker->showInfo(); worker = new Manager(2, " Li Si ", 2); worker->showInfo(); delete worker; worker = new Boss(3, " Shiyuan ", 3); worker->showInfo(); delete worker;*/
	//  Instantiate the manager object 
	WorkerManager wm;
	//  Call the display menu member function 
	int choice = 0;
	while (true)
	{
    
		wm.Show_Menu();
		cout << " Please enter your choice :" << endl;
		cin >> choice;
		switch (choice)
		{
    
		case 0:       //  Exit the system 
			wm.Exit_System();
			break;   
		case 1:       //  Increase staff 
			wm.Add_Emp();
			break;
		case 2:       //  Show employees 
			wm.show_Emp();
			break;
		case 3:       //  Delete employees 
			wm.Del_Emp();
			break;
		case 4:       //  Modify the staff 
			wm.Mod_Emp();
			break;
		case 5:       //  Find employees 
			wm.Find_Emp();
			break;
		case 6:       //  Sort by employee number 
			wm.Sort_Emp();
			break;
		case 7:       //  Empty all documents 
			wm.Clean_File();
			break;
		default:
			system("cls");
			break;
		}
	}
	
	system("pause");
	return 0;
}

Describe the contents of each customized header file separately

  • Worker_Manager.h: The function declaration of all function functions in the main function is encapsulated by a class , The specific functions are implemented in Worker_Manager.cpp in .
  • Worker.h: Defines an abstract class of employees . These include :
    • Two pure virtual functions : Display employee information and obtain position name
    • Some basic attributes of employees : There are employee names , Employee number and employee department number .
    • employee.h: Employee subcategory , Inherited the Employee class , Rewrite two pure virtual functions in the Employee class , A function declaration is made ,manager.h and boss.h So it is with

Implementation of function

#include"Worker_Manager.h"
#include"boss.h"
#include"employee.h"
#include"Worker.h"
#include"manager.h"
WorkerManager::WorkerManager()
{
    
	//  Initialization property 
	// 1、 file does not exist 
	ifstream ifs;
	ifs.open(FILENAME, ios::in);
	if (!ifs.is_open())
	{
    
		cout << " file does not exist " << endl;
		this->m_EmpNum = 0;  //  Initialization records the number of people 
		this->m_EmpArray = NULL;   //  Initialize array pointer 
		this->m_FileIsEmpty = true; //  Whether the initialization file is empty 
		ifs.close();
		return;
	}
	// 2、 File exists   Data is empty 
	char ch;
	ifs >> ch; //  Move the stream object right one character 
	if (ifs.eof())
	{
    
		cout << " The file is empty !" << endl;
		this->m_EmpNum = 0;  //  Initialization records the number of people 
		this->m_EmpArray = NULL;   //  Initialize array pointer 
		this->m_FileIsEmpty = true; //  Whether the initialization file is empty 
		ifs.close();
		return;
	}
	// 3、 When the file exists and is not empty 
	int num = this->get_EmpNum();  //  Get the current number of employees 
	cout << " The number of employees is :" << num << endl;
	this->m_EmpNum = num;
	//  Open up space 
	this->m_EmpArray = new Worker * [this->m_EmpNum];  //  Open up a block of memory in the heap to store pointer variables pointing to employees 
	//  Put the data in the file , Put it in an array 
	this->init_Emp();
	//  Test code 
	/* for (int i = 0; i < this->m_EmpNum; i++) { cout << "  Employee number :" << this->m_EmpArray[i]->m_id << "  full name :" << this->m_EmpArray[i]->m_name << "  Department number :" << this->m_EmpArray[i]->m_deptid << endl; } */
}

void WorkerManager::Show_Menu()
{
    
	cout << "*************************************************************" << endl;
	cout << "**************  Welcome to the employee management system ! ************************" << endl;
	cout << "**************** 0.  Exit management program  ***************************" << endl;
	cout << "**************** 1.  Add employee information  ***************************" << endl;
	cout << "**************** 2.  Display employee information  ***************************" << endl;
	cout << "**************** 3.  Delete the resigned employee  ***************************" << endl;
	cout << "**************** 4.  Modify employee information  ***************************" << endl;
	cout << "**************** 5.  Find employee information  ***************************" << endl;
	cout << "**************** 6.  Sort by number  ***************************" << endl;
	cout << "**************** 7.  Empty all documents  ***************************" << endl;
	cout << "*************************************************************" << endl;
	cout << endl;
}

void WorkerManager::Exit_System()
{
    
	cout << " Welcome to use next time !" << endl;
	system("pause");
	exit(0);  //  Exit procedure 
}

void WorkerManager::Add_Emp()
{
    
	cout << " Please enter the number of employees to be added :" << endl;
	int addNum = 0; //  Save the number of user inputs 
	cin >> addNum;

	if (addNum > 0)
	{
    
		//  add to 
		//  Calculate the size of the new space added 
		int newSize = this->m_EmpNum + addNum;
		//  Open up new space 
		Worker ** newSpace =  new Worker* [newSize];
		//  The data in the original space , Copy to a new space 
		if (this->m_EmpArray != NULL)
		{
    
			for (int i = 0; i < this->m_EmpNum; i++)
			{
    
				newSpace[i] = this->m_EmpArray[i];
			}
		}

		//  Add new data 
		for (int i = 0; i < addNum; i++)
		{
    
			int id;
			string name;
			int DSelect;

			cout << " Please enter the first  " << i + 1 << "  A new employee number :" << endl;
			cin >> id;

			cout << " Please enter the first  " << i + 1 << "  The name of a new employee :" << endl;
			cin >> name;

			cout << " Please select the position :" << endl;
			cout << "1、 Ordinary employees " << endl;
			cout << "2、 The manager " << endl;
			cout << "3、 Boss " << endl;
			cin >> DSelect;

			Worker* worker = NULL;
			switch (DSelect)
			{
    
			case 1:
				worker = new Employee(id, name, 1);
				break;
			case 2:
				worker = new Manager(id, name, 2);
				break;
			case 3:
				worker = new Boss(id, name, 3);
				break;
			default:
				break;
			}
			// Employee pointer to be created ,, Save to the array 
			newSpace[this->m_EmpNum + i] = worker;
		}
		//  Release the original space 
		delete[] this->m_EmpArray;

		//  Change the direction of the new space 
		this->m_EmpArray = newSpace;

		//  Update the number of new employees 
		this->m_EmpNum = newSize;

		//  Update the flag that the employee is not empty 
		this->m_FileIsEmpty = false;
		//  Prompt to add successfully 
		cout << " Successful addition " << addNum << " A new employee " << endl;

		//  Save the data to a file 
		this->save();
	}
	else
	{
    
		cout << " Wrong input data !" << endl;
	}

	//  Press any key to clear the screen 
	system("pause");
	system("cls");
}

//  Save the file 
void WorkerManager::save()
{
    
	ofstream ofs;
	ofs.open(FILENAME, ios::out);

	//  Write everyone's data to a file 
	for (int i = 0; i < this->m_EmpNum; i++)
	{
    
		ofs << this->m_EmpArray[i]->m_id << " "
			<< this->m_EmpArray[i]->m_name << " "
			<< this->m_EmpArray[i]->m_deptid << endl;
	}
	ofs.close();
}

//  The number of people in the statistical file 
int WorkerManager::get_EmpNum()
{
    
	ifstream ifs;
	ifs.open(FILENAME, ios::in);
	int id;
	string name;
	int did;
	int num = 0;

	while (ifs >> id && ifs >> name && ifs >> did)
	{
    
		//  Statistical population variables 
		num++;
	}
	return num;
}

//  Initialize employees 
void WorkerManager::init_Emp()
{
    
	ifstream ifs;
	ifs.open(FILENAME, ios::in);

	int id;
	string name;
	int did;
	int index = 0;

	while (ifs >> id && ifs >> name && ifs >> did)
	{
    
		Worker* worker = NULL;
		if (did == 1)
		{
    
			worker = new Employee(id, name, did);  //  by employee Open up a memory space in the heap , Pointer to the variable worker Pointing to it 
		}
		else if (did == 2)
		{
    
			worker = new Manager(id, name, did);
		}
		else
		{
    
			worker = new Boss(id, name, did);
		}
		this->m_EmpArray[index] = worker;  //  take worker The pointer is stored in the array pointer 
		index++;
	}
	ifs.close();
}

//  Show employees 
void WorkerManager::show_Emp()
{
    
	//  Determine if the file is empty 
	if (this->m_FileIsEmpty)
	{
    
		cout << " The file does not exist or the record is empty !" << endl;
	}
	else
	{
    
		for (int i = 0; i < m_EmpNum; i++)
		{
    
			//  Using polymorphism to call program interface 
			this->m_EmpArray[i]->showInfo();
		}
	}
	//  Press any key to clear the screen 
	system("pause");
	system("cls");
}

//  Delete employees 
void WorkerManager::Del_Emp()
{
    
	if (this->m_FileIsEmpty)
	{
    
		cout << " The file is empty or does not exist !" << endl;
	}
	else
	{
    
		//  Delete by employee number 
		cout << " Please enter the employee number to delete :" << endl;
		int id = 0;
		cin >> id;
		int temp = IsExist(id);
		if (temp != -1)
		{
    
			while (temp < this->m_EmpNum)
			{
    
				this->m_EmpArray[temp] = this->m_EmpArray[temp + 1];
				temp++;
			}
			this->m_EmpNum--;    //  Update the number of people recorded in the array 
			//  Synchronize updates to files 
			this->save();
			cout << " Delete successful !" << endl;
		}
		else
		{
    
			cout << " Delete failed ! The employee was not found !" << endl;
		}
	}

	//  Press any key to clear the screen 
	system("pause");
	system("cls");
}

	//  Judge whether employees exist   If it exists, return the position of the employee in the array , There is no return -1
int WorkerManager::IsExist(int id)
{
    
	int index = -1;
	for (int i = 0; i < this->m_EmpNum; i++)
	{
    
		if (this->m_EmpArray[i]->m_id == id)
		{
    
			//  Find employees 
			index = i;
			break;
		}
	}
	return index;
}

//  Modify the staff 
void WorkerManager::Mod_Emp()
{
    
	if (this->m_FileIsEmpty)
	{
    
		cout << " File does not exist or file is empty !" << endl;
	}
	else
	{
    
		cout << " Please enter the number of the modified employee :" << endl;
		int id;
		cin >> id;
		int temp = IsExist(id);
		if (temp != -1)
		{
    
			//  Find the employee number 
			delete this->m_EmpArray[temp];
			int newid = 0;
			string newname = "";
			int dselect = 0;
			cout << " find out :" << id << " Employee No , Please enter the new employee number :" << endl;
			cin >> newid;
			cout << " Please enter a new name :" << endl;
			cin >> newname;
			cout << " Please enter a new position :" << endl;
			cout << "1、 Ordinary employees " << endl;
			cout << "2、 The manager " << endl;
			cout << "3、 Boss " << endl;
			cin >> dselect;

			Worker* worker = NULL;
			switch (dselect)
			{
    
			case 1:
				worker = new Employee(newid, newname, dselect);
				break;
			case 2:
				worker = new Manager(newid, newname, dselect);
				break;
			case 3:
				worker = new Boss(newid, newname, dselect);
				break;
			default:
				break;
			}
			//  Update data to array 
			this->m_EmpArray[temp] = worker;
			cout << " Modification successful !" << endl;
			//  Save to file 
			this->save();
		}
		else
		{
    
			cout << " Modification failed , Check no one !" << endl;
		}
	}
	system("pause");
	system("cls");
}

//  Find employees 
void WorkerManager::Find_Emp()
{
    
	if (this->m_FileIsEmpty)
	{
    
		cout << " The file is empty or does not exist !" << endl;
	}
	else
	{
    
		cout << " Please enter the search method :" << endl;
		cout << "1、 Search by employee number " << endl;
		cout << "2、 Search by employee's name " << endl;

		int select = 0;
		cin >> select;

		if (select == 1)
		{
    
			//  Check by the number 
			int id;
			cout << " Please enter the employee number to find :" << endl;
			cin >> id;

			int ret = IsExist(id);
			if (ret != -1)
			{
    
				//  Find employees 
				cout << " Find success ! The employee's information is as follows :" << endl;
				this->m_EmpArray[ret]->showInfo();
			}
			else
			{
    
				cout << " To find the failure ! Check no one !" << endl;
			}
		}
		else if (select == 2)
		{
    
			string name;
			cout << " Please enter the name of the employee you want to find :" << endl;
			cin >> name;

			//  Add a flag to judge whether it is found 
			bool flag = false; //  Default no employee found 

			for (int i = 0; i < m_EmpNum; i++)
			{
    
				if (this->m_EmpArray[i]->m_name == name)
				{
    
					cout << " Find success ! The employee number is :" << this->m_EmpArray[i]->m_id << "\t The employee's information is as follows :" << endl;
					flag = true;
					this->m_EmpArray[i]->showInfo();  //  Call the display information interface 
				}
			}
			if (flag == false)
			{
    
				cout << " To find the failure , Check no one !" << endl;
			}
		}
		else
		{
    
			cout << " Wrong option entered !" << endl;
		}
	}
	//  Press any key to clear the screen 
	system("pause");
	system("cls");
}


//  Sort by employee number 
void WorkerManager::Sort_Emp()
{
    
	if (this->m_FileIsEmpty)
	{
    
		cout << " The file does not exist or the record is empty !" << endl;
		system("pause");
		system("cls");
	}
	else
	{
    
		cout << " Please select sort by :" << endl;
		cout << "1、 Sort by employee number in ascending order " << endl;
		cout << "2、 Sort by employee number in descending order " << endl;

		int select = 0;
		cin >> select;
		for (int i = 0; i < m_EmpNum; i++)
		{
    
			int minormax = i;    //  Declare the minimum or maximum subscript 
			for (int j = i + 1; j < this->m_EmpNum; j++)
			{
    
				if (select == 1)
				{
    
					if (this->m_EmpArray[minormax]->m_id > this->m_EmpArray[j]->m_id)
					{
    
						minormax = j;
					}
				}
				else
				{
    
					if (this->m_EmpArray[minormax]->m_id < this->m_EmpArray[j]->m_id)
					{
    
						minormax = j;
					}
				}
			}
			//  Judge whether the minimum or maximum value recognized at the beginning is the calculated minimum or maximum value , If not , Exchange data 
			if (i != minormax)
			{
    
				Worker* temp = this->m_EmpArray[i];
				this->m_EmpArray[i] = this->m_EmpArray[minormax];
				this->m_EmpArray[minormax] = temp;
			}
		}
		cout << " Sort success ! The sorted result is :" << endl;
		this->save(); //  Save the sorting results to a file 
		this->show_Emp();   //  Show all employees 
	}
}

//  Empty files 
void WorkerManager::Clean_File()
{
    
	cout << " Make sure to clear ?" << endl;
	cout << "1、 determine " << endl;
	cout << "2、 return " << endl;

	int select = 0;
	cin >> select;
	if (select == 1)
	{
    
		//  Empty files 
		ofstream ofs(FILENAME, ios::trunc); //  Delete the file and create it again 
		ofs.close();
		if (this->m_EmpArray != NULL)
		{
    
			for (int i = 0; i < this->m_EmpNum; i++)  //  Delete every worker object in the heap 
			{
    
				if (this->m_EmpArray[i] != NULL)
				{
    
					delete this->m_EmpArray[i];
					this->m_EmpArray[i] = NULL;
				}
			}
			//  Delete the array pointer of the heap 
			delete[] this->m_EmpArray;
			this->m_EmpArray = NULL;
			this->m_EmpNum = 0;
			this->m_FileIsEmpty = true;
		}
		cout << " Empty successfully !" << endl;
	}
	system("pause");
	system("cls");
}

WorkerManager::~WorkerManager()
{
    
	if (this->m_EmpArray != NULL)
	{
    
		for (int i = 0; i < this->m_EmpNum; i++)
		{
    
			if (this->m_EmpArray[i] != NULL)
			{
    
				delete this->m_EmpArray[i];
				this->m_EmpArray[i] = NULL;
			}	
		}
		delete[] this->m_EmpArray;
		this->m_EmpArray = NULL;
		this->m_EmpNum = 0;
		this->m_FileIsEmpty = true;
	}
}

On the role of virtual functions and implementation principles

  • First , The function of virtual function is to realize polymorphism .C++ In fact, the polymorphism of is to add... Before the function of the base class virtual keyword , Override the function in a derived class .
  • The corresponding function will be called according to the actual type of the object , If the object type is a derived class , Call the function of the derived class , If the object is a base class , Call the functions of the base class .
  • Polymorphism is divided into static polymorphism and dynamic polymorphism .
    • Static polymorphism is performed during the compiler , The compiler depends on the type of function arguments , Infer which function to call .
    • Dynamic polymorphism is the process of executing a program while it is running , Determine the actual type of the object , Then call the corresponding method .
  • The second function is when a function in the parent class needs to be overridden in the child class , It is defined as a virtual function in the parent class .
  • The third function is when defining a parent class pointer to a child class , Can dynamically call a subclass of ( Be rewritten ) Function of .

Realization principle

  • When the compiler finds that the parent class has virtual functions , It will automatically generate a virtual table for each class containing virtual functions , This table is an ordinary one-dimensional array , The virtual table contains The entry address of the virtual function .
  • Then the compiler instantiates the object , A virtual table pointer will be saved in the first four bytes of each object , Points to the virtual table of the class to which the object belongs .
  • Then when the parent class calls the subclass method , Virtual pointer and virtual table will be called .

Summary

This project sharing and the principle of polymorphism and function realization involved in it are the above . So far, only the main part of the code has been shared , I will upload all the project codes to the resources , Try to set the minimum points to download .

copyright notice
author[loveCC_ orange],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/175/202206240754241640.html

Random recommended