C++ 银行账户管理系统:实现资金往来账目功能
以下是一个使用 C++ 语言编写的实现银行账户管理系统的示例代码,该系统包含创建账户、存取款、查询交易明细等功能。
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
struct Transaction {
time_t date;
double amount;
};
class Bank {
private:
string accountNumber;
time_t creationDate;
double balance;
vector<Transaction> transactions;
public:
Bank(string accountNumber, double initialBalance) {
this->accountNumber = accountNumber;
this->creationDate = time(nullptr);
this->balance = initialBalance;
}
void deposit(double amount) {
balance += amount;
Transaction transaction;
transaction.date = time(nullptr);
transaction.amount = amount;
transactions.push_back(transaction);
}
void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
Transaction transaction;
transaction.date = time(nullptr);
transaction.amount = -amount;
transactions.push_back(transaction);
} else {
cout << 'Insufficient balance.' << endl;
}
}
void printTransactions() {
time_t currentTime = time(nullptr);
time_t oneMonthAgo = currentTime - 30 * 24 * 60 * 60;
cout << 'Account transactions for the last month:' << endl;
for (const Transaction& transaction : transactions) {
if (transaction.date >= oneMonthAgo) {
cout << 'Date: ' << ctime(&transaction.date);
cout << 'Amount: ' << transaction.amount << endl;
}
}
}
};
int main() {
Bank bank('1234567890', 1000.0);
bank.deposit(500.0);
bank.withdraw(200.0);
bank.printTransactions();
return 0;
}
该代码定义了一个 Bank 类,其中包含了账户号码 (accountNumber)、创建日期 (creationDate)、余额 (balance) 和交易记录 (transactions) 等属性。构造函数用于初始化账户号码和初始余额。存钱 (deposit) 和取钱 (withdraw) 方法分别用于执行存钱和取钱操作,并记录相应的日期和金额。查询交易明细 (printTransactions) 方法用于打印近一个月的交易记录。
在 main 函数中,创建了一个 Bank 对象,并进行了存钱和取钱的操作,最后调用了 printTransactions 方法打印交易明细。
注意:由于时间的处理比较复杂,上述代码中使用了 ctime 函数将时间转换为字符串进行输出。在实际开发中,可能需要根据具体需求使用更合适的时间处理方式。
原文地址: https://www.cveoy.top/t/topic/f3Zy 著作权归作者所有。请勿转载和采集!