C++设计一个bank类,实现银行某账号的资金往来账目管理
时间: 2024-10-20 16:16:09 浏览: 37
在C++中设计一个Bank类,用于管理银行账户的转账操作,我们可以考虑以下几个关键部分:
```cpp
#include <string>
#include <vector>
class Account {
private:
std::string account_number;
double balance;
public:
// 构造函数
Account(const std::string& accountNum, double initialBalance)
: account_number(accountNum), balance(initialBalance) {}
// 获取账户号
std::string getAccountNumber() const { return account_number; }
// 设置和获取余额
void setBalance(double newBalance) { balance = newBalance; }
double getBalance() const { return balance; }
// 转账方法
void transfer(Account& other, double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
other.setBalance(other.getBalance() + amount);
} else {
throw std::invalid_argument("Insufficient funds or invalid transfer amount");
}
}
};
// Bank 类,管理多个账户
class Bank {
private:
std::vector<Account> accounts;
public:
// 添加新账户
void addAccount(const std::string& accountNum, double initialBalance) {
accounts.push_back(Account(accountNum, initialBalance));
}
// 根据账户号找到并操作账户
void operateAccount(const std::string& accountNum, double action, Account* targetAccount) {
for (Account& account : accounts) {
if (account.getAccountNumber() == accountNum) {
if (action == "deposit") {
targetAccount->setBalance(targetAccount->getBalance() + action_amount);
} else if (action == "withdraw" || action == "transfer") {
targetAccount->transfer(*targetAccount, action_amount);
}
break;
}
}
}
};
```
在这个例子中,我们首先定义了一个`Account`类,包含了账户号和余额属性,以及转账、存款和取款方法。然后在`Bank`类中,维护了一个`Account`的集合,并提供了添加账户和通过账户号执行操作的功能。
阅读全文