前言
C++入门案例——基于多态的职工管理系统 & 控制台项目
目录
基于多态的职工管理系统
基于多态的类设计
#pragma once
#include<iostream>
#include<string>
using namespace std;
// 职工的抽象的类
class Worker
{
public:
// 职工的编号等
int id;
string name;
int dep;
// 方法
virtual void showInfo() = 0;
virtual string getDeptment() = 0;
};
#pragma once
#include<iostream>
#include<string>
#include "worker.h"
using namespace std;
class Boss : public Worker
{
public:
// 构造函数
Boss(int id, string name, int dId);
// 方法, virtual 可删可不删
virtual void showInfo();
virtual string getDeptment();
};
#include "boss.h"
// 构造函数
Boss::Boss(int id, string name, int dId) {
this->id = id;
this->name = name;
this->dep = dId;
}
// 显示信息
void Boss::showInfo() {
cout << "职工编号:" << this->id
<< "\t职工姓名:" << this->name
<< "\t岗位:" << this->getDeptment()
<< "\t岗位职责:老板"
<< endl;
}
// 获取部门
string Boss::getDeptment() {
return string("老板");
}
基于接口与实现分离的设计
具体的实现
类设计
职工的抽象类
virtual关键字,定义为虚函数,在运行时,根据对象的类型来确定调用具体的哪一个函数,这种能力叫做C++的多态性
#pragma once
#include<iostream>
#include<string>
using namespace std;
// 职工的抽象的类
class Worker
{
public:
// 职工的编号等
int id;
string name;
int dep;
// 方法
virtual void showInfo() = 0;
virtual string getDeptment() = 0;
};
老板,经理,普通员工继承自抽象类
#pragma once
#include<iostream>
#include<string>
#include "worker.h"
using namespace std;
class Manager : public Worker
{
public:
// 构造函数
Manager(int id, string name, int dId);
// 方法, virtual 可删可不删
virtual void showInfo();
virtual string getDeptment();
};
类的实现
#include "manager.h"
Manager::Manager(int id, string name, int dId)
{
this->id = id;
this->name = name;
this->dep = dId;
}
void Manager::showInfo()
{
cout << "职工编号:" << this->id
<< "\t职工姓名:" << this->name
<< "\t岗位:" << this->getDeptment()
<< "\t岗位职责:服从老板,安排员工干活"
<< endl;
}
string Manager::getDeptment()
{
return string("经理");
}
主程序
头文件中定义接口
在头文件中定义显示菜单的页面接口,员工管理相关的显示员工,增删改查等相关操作,另外包括文件交互,把员工的相关信息存储到txt文本文件中。
#pragma once // 防止头文件重复包含
#include<iostream> // 包含输入和输出流的头文件
using namespace std; // 使用标准命名空间
#include "worker.h"
#include "emp.h"
#include "manager.h"
#include "boss.h"
#include <fstream>
#define FILENAME "workerNo.txt"
class WorkerManager
{
public:
// 构造函数
WorkerManager();
// 展示菜单
void ShowMenu();
// 显示员工
void ShowEmp();
// 退出程序
void exitSystem();
// 记录职工人数
int workerNum;
// 职工的数组
Worker ** workerArray;
void addWorker();
// 保存文件,持久化
void save();
bool isFileEmpty;
// 统计人数
int getWorkerNum();
// 初始化员工
void initWorker();
// 删除职工
void delEmp();
// 判断职工是否存在
int isExist(int id);
// 修改员工
void updateEmp();
// 查找员工
void findEmp();
// 按照编号排序
void sortEmp();
// 清空文件
void cleanFile();
// 析构函数
~WorkerManager();
};
cpp文件中具体实现
#include "workerManage.h"
WorkerManager::WorkerManager()
{
// 文件不存在</