最近在复习 C++ 基础知识,遇到了这个案例,这个案例涵盖了 C++ 很多重要的知识,如果有需要可以参考,代码和书中的一样。
程序分为 6 个文件:date.h 是日期类头文件,date.cpp 是日期类实现文件,accumulator.h 是为按日将数值累加的 Accumulator 类的头文件,account.h 是各个储蓄账户类定义头文件,account.cpp 是各个储蓄账户类实现文件,还有一个是主文件。代码如下:
//==========================================
// Filename : 个人银行账户管理程序
// Time : 2019年4月30日
// Authonr : 柚子树
// Email : gz_duyong@163.com
//==========================================
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cmath>
#include "account.h"
#include <vector>
#include <algorithm>
using namespace std;
struct deleter
{
template<class T>
void operator()(T *p) {
delete p; }
};
class Controller // 控制器,用来存储账户列表和处理命令
{
private:
Date date; // 当前日期
vector<Account*>accounts; // 账户列表
bool end; // 用户是否输入了退出指令
public:
Controller(const Date &date) : date(date), end(false) {
}
~Controller();
const Date &getDate() const {
return date; }
bool isEnd() const {
return end; }
// 执行一条命令,返回该命令是否改变了当前状态(即是否需要保存该命令)
bool runCommand(const string &cmdLine);
};
Controller::~Controller()
{
for_each(accounts.begin(), accounts.end(), deleter());
}
bool Controller::runCommand(const string &cmdLine)
{
istringstream str(cmdLine);
char cmd, type;
int index, day;
double amount, credit, rate, fee;
string id, desc;
Account *account;
Date date1, date2;
str >> cmd;
switch (cmd)
{
case 'a': // 增加账户
str >> type >> id;
if (type == 's')
{
str >> rate;
account = new SavingAccount(date, id, rate);
}
else
{
str >> credit >> rate >> fee;
account = new CreditAccount(date, id, credit, rate, fee);
}
accounts.push_back(account);
return true;
case 'd': // 存入现金
str >> index >> amount;
getline(str, desc);
accounts[index]->deposit(date, amount, desc);
return true;
case 'w': // 取出现金
str >> index >> amount;
getline(str, desc);
accounts[index]->withdraw(date, amount, desc);
return true;
case 's': // 查询各账户信息
for (size_t i = 0; i < accounts.size(); i++)
{
cout << "[" << i << "]";
accounts[i]->show(cout);
cout << endl;
}
return false;
case 'c': // 改变日期
str >> day;
if (day < date.getDay())
{
cout << "You cannot specify a previous day";
}
else if (day > date.getMaxDay())
{
cout << "Invalid day";
}
else
{
date = Date(date.getYear(), date.getMonth(), day);
}
return true;
case 'n': // 进入下个月
if (date.getMonth() == 12)
{
date = Date(date.getYear() + 1, 1, 1);
}
else
{
date = Date(date.getYear(), date.getMonth() + 1, 1);
}
for (vector<Account*>::iterator iter = accounts.begin();
iter != accounts.end(); ++iter)
{
(*iter)->settle(date);
}
return true;
case 'q': // 查询一段时间内的账目
str >> date1 >> date2;
Account::query(date1