C++学习(c++17)——1.3 一个小程序(part1.Employee类)
前言
今天是reStudy的第三天。我准备利用毕(假)生(期)所学来试试写点东西。——说实话,假期看网课的时候虽然也想实践,但看视频和敲代码切换来切换去,很快就感觉厌烦了。还是拿着文档时候能静下心来学习。结束了前面的概述,现在来尝试用对象的思想做一个真正有用的程序(指课设,顺带吐槽一下上学期的面向过程的学生管理系统代码敲得是真的烂)。
要求
管理公司雇员记录的程序应该灵活并具有有效的功能。这个程序包含的功能有:
- 添加雇员
- 解雇雇员
- 雇员晋升
- 查看所有雇员(包括过去和现在的)
- 查看所有当前雇员
- 查看所有以前(已解雇)雇员
思路
整体包含 雇员 这个类,用类写一个仿数据库来储存数据,还有用户界面提供程序的接口
(致初学者:此章涉及知识点:
-
)
实现
Employee.h
#pragma once
#include <string>
namespace Records {
const int kDefaultStartingSalary = 30000;
class Employee
{
public:
Employee();
Employee(const std::string fisrtName, const std::string lastName);
void promote(int raiseAmount);//增薪,减薪,雇佣,炒鱿鱼
void demote(int demeritAmount);
void hire();
void fire();
void setSalary(int newSalary);//对fistName,lastName,employeeNumber,Salary的get和set
const int getSalary();
void setFirstName(const std::string newFirstName);
const std::string getFirstName();
void setLastName(const std::string newLastName);
const std::string getLastName();
void setEmployeeNumber(int employeeNumber);
const int getEmployeeNumber();
const bool isHired();//查看是否被炒
void display();//显示 某职员信息
private://初始化职员的默认资料
std::string mFirstName;
std::string mLastName;
int mEmployeeNumber = -1;
int mSalary = kDefaultStartingSalary;
bool mHired = false;
};
}
Employee.cpp
#include <iostream>
#include "Employee.h"
using namespace std;
namespace Records {
Employee::Employee(const string firstName, const string lastName)//引用与否
:mFirstName(firstName), mLastName(lastName) {
}
void Employee::setSalary(int newSalary){
mSalary = newSalary;
}
const int Employee::getSalary(){//const位置
return mSalary;
}
void Employee::promote(int raiseAmount) {
setSalary(getSalary() + raiseAmount);
}
void Employee::demote(int demeritAmount) {
setSalary(getSalary() - demeritAmount);
}
void Employee::hire() {
mHired = true;
}
void Employee::fire() {
mHired = false;
}
void Employee::setFirstName(const std::string newFirstName) {
mFirstName = newFirstName;
}
const std::string Employee::getFirstName() {
return mFirstName;
}
void Employee::setLastName(const std::string newLastName) {
mLastName = newLastName;
}
const std::string Employee::getLastName() {
return mLastName;
}
void Employee::setEmployeeNumber(int employeeNumber) {
mEmployeeNumber = employeeNumber;
}
const int Employee::getEmployeeNumber() {
return mEmployeeNumber;
}
const bool Employee::isHired() {
return mHired;
}
void Employee::display() {
cout << "Employee: " << getFirstName() << ", " << getLastName() << endl;
cout << "--------------------" << endl;
cout << (isHired() ? "Current Employee" : "Former Employee") << endl;
cout << "Employee Number: " << getEmployeeNumber() << endl;
cout << "Salary: " << getSalary() << endl;
cout << endl;
}
}
main函数测试
#include "Employee.h"
#include <iostream>
using namespace std;
using namespace Records;
int main()
{
Employee emp("John","Daw");
emp.setSalary(900);
emp.setEmployeeNumber(1);
emp.hire();
emp.promote(50);
emp.demote(25);
emp.display();
return 0;
}
成功了,虽然是很基础的一个程序。