Database的实现
Database.h
#pragma once
#include<iostream>
#include<vector>
#include"Employee.h"
namespace Records {
const int kFirstEmployeeNumber = 1000;
class Database
{
public:
Employee& addEmployee( std::string firstName, std::string lastName);
Employee getEmployee( int employeeNumber);
Employee getEmployee(std::string firstName, std::string lastName);
void displayAll();
void displayCurrent();
void displayFormer();
private:
std::vector<Employee> mEmployees;
int mNextEmployeeNumber = kFirstEmployeeNumber;
};
}
Database.cpp
#include<iostream>
#include<stdexcept>
#include"Database.h"
namespace Records {
Employee& Database::addEmployee( std::string firstName, std::string lastName) {
Employee theEmployee(firstName, lastName);
theEmployee.setEmployeeNumber(mNextEmployeeNumber++);//每个数据库对象的这个从1000开始加
theEmployee.hire();
mEmployees.push_back(theEmployee);
return mEmployees[mEmployees.size() - 1];//返回最后一个
}
Employee Database::getEmployee(int employeeNumber) {
for ( auto employee : mEmployees) {
if (employee.getEmployeeNumber() == employeeNumber) {
return employee;
}
}
throw std::logic_error("No employee found(number)");
}
Employee Database::getEmployee(std::string firstName, std::string lastName) {
for ( auto employee : mEmployees) {
if (employee.getFirstName()== firstName && employee.getLastName() == lastName) {
return employee;
}
}
throw std::logic_error("No employee found(name)");
}
void Database::displayAll() {
for (auto employee : mEmployees) {
employee.display();
}
}
void Database::displayCurrent() {
for (auto employee : mEmployees) {
if (employee.isHired()) employee.display();
}
}
void Database::displayFormer() {
for (auto employee : mEmployees) {
if (!employee.isHired()) employee.display();
}
}
}
main.cpp
// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "Employee.h"
#include <iostream>
#include "Database.h"
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; */
Database myDB;
Employee emp1 = myDB.addEmployee("Greg", "Wallis");
emp1.fire();
Employee& emp2 = myDB.addEmployee("Marc","White");
emp2.setSalary(10000);
Employee& emp3 = myDB.addEmployee("John", "Doe");
emp3.setSalary(1000);
emp3.promote();
myDB.displayAll();
std::cout << std::endl;
myDB.displayCurrent();
std::cout << std::endl;
myDB.displayFormer();
}
一开始Database::addEmployee类型忘记加引用&了,导致后面的fire和setSalary、promote都是对临时对象进行,而不会对myDB里的数据进行操作。
原帖地址**: https://www.cnblogs.com/ranbom/
博主LeoRanbom
只在原帖地址的博客上发布,其他地方看到均为爬取。
如果觉得不错希望来点个赞。