写两层类的银行账号管理系统c++代码
时间: 2023-11-04 19:18:54 浏览: 125
以下是一个简单的银行账号管理系统的C++代码,包含两个类:BankAccount和Bank。BankAccount类表示单个银行账户,Bank类表示整个银行的管理系统。
```c++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class BankAccount {
private:
string name;
int accountNumber;
double balance;
public:
BankAccount(string n, int num, double bal) {
name = n;
accountNumber = num;
balance = bal;
}
string getName() {
return name;
}
int getAccountNumber() {
return accountNumber;
}
double getBalance() {
return balance;
}
void deposit(double amount) {
balance += amount;
}
void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
} else {
cout << "Insufficient balance!" << endl;
}
}
void display() {
cout << "Name: " << name << endl;
cout << "Account Number: " << accountNumber << endl;
cout << "Balance: " << balance << endl;
}
};
class Bank {
private:
vector<BankAccount> accounts;
public:
void addAccount(string name, int accountNumber, double balance) {
BankAccount account(name, accountNumber, balance);
accounts.push_back(account);
}
void removeAccount(int accountNumber) {
for (int i = 0; i < accounts.size(); i++) {
if (accounts[i].getAccountNumber() == accountNumber) {
accounts.erase(accounts.begin() + i);
cout << "Account removed." << endl;
return;
}
}
cout << "Account not found." << endl;
}
void displayAll() {
for (int i = 0; i < accounts.size(); i++) {
accounts[i].display();
cout << endl;
}
}
BankAccount* findAccount(int accountNumber) {
for (int i = 0; i < accounts.size(); i++) {
if (accounts[i].getAccountNumber() == accountNumber) {
return &accounts[i];
}
}
return NULL;
}
};
int main() {
Bank bank;
bank.addAccount("Alice", 1001, 1000);
bank.addAccount("Bob", 1002, 2000);
bank.addAccount("Charlie", 1003, 3000);
bank.displayAll();
BankAccount* account = bank.findAccount(1002);
if (account != NULL) {
account->deposit(500);
account->display();
}
bank.removeAccount(1003);
bank.displayAll();
return 0;
}
```
在该代码中,BankAccount类包含了银行账户的基本信息和操作方法。Bank类则包含了整个银行账户的管理系统,包括添加、删除和查找账户等方法。在main函数中,我们可以看到如何使用这两个类来管理银行账户。
阅读全文