代码
/**
* c++声明一个银行账号类Account
* 该类有账号(id)、余额(balance)两个数据成员,
* 有获取账号、获取余额、存款和取款的函数,以及必要的构造函数。
* 请按上述要求:
* 声明该银行账号类并在main函数中定义该类的多个对象,
* 然后对它们进行存取款和查询余额的操作。
*/
#include <iostream>
#include <mutex>
#include <sstream>
#include <string>
#include <vector>
class account_t {
public:
account_t(const std::string& id) {
_id = id;
_balance = 0;
_writer << "================================================" << std::endl
<< "[ create ] " << _id;
_logs.push_back(_writer.str());
_writer.str("");
}
~account_t() {
_writer << "[ delete ] " << _id << std::endl
<< "------------------------------------------------" << std::endl
<< "final balance : " << _balance << std::endl
<< "================================================" << std::endl;
_logs.push_back(_writer.str());
_writer.str("");
dump();
}
account_t(const account_t& rhs) = delete;
account_t& operator=(const account_t& rhs) = delete;
// getters
public:
const std::string& id() const { return _id; }
void dump() {
for (const auto& log : _logs) { std::cout << log << std::endl; }
}
public:
double balance() {
std::lock_guard<std::mutex> lock(_mutex);
return _balance;
}
void deposit(double amount) {
std::lock_guard<std::mutex> lock(_mutex);
amount = trim(amount);
if (amount <= 0) return;
_balance = _balance + amount;
_writer << "[ deposit ] " << amount << ", with balance of " << _balance;
_logs.push_back(_writer.str());
_writer.str("");
}
void withdraw(double amount) {
std::lock_guard<std::mutex> lock(_mutex);
amount = trim(amount);
if (amount <= 0 || amount > _balance) return;
_balance = _balance - amount;
_writer << "[ withdraw ] " << amount << ", with balance of " << _balance;
_logs.push_back(_writer.str());
_writer.str("");
}
protected:
double trim(double amount) {
int _amount = amount * 1000;
return _amount / 1000.0f;
}
private:
std::string _id;
double _balance;
std::mutex _mutex;
std::vector<std::string> _logs;
std::stringstream _writer;
};
int main(int argc, char const* argv[]) {
std::vector<std::string> ids = {
"402674 8234 8239 384", "622892 8234 8239 384"};
for (const auto& id : ids) {
auto account = new account_t(id);
for (int it = 0; it < 5; it++) {
account->deposit(std::rand() * 1000.0f / RAND_MAX);
account->withdraw(std::rand() * 1000.0f / RAND_MAX);
}
delete account;
}
return system("pause");
}
结果
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/9a504fc2d56285352f30543c9aef76c6a6ef63df?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)