设计一个简单银行账户系统,可完成开户、存款、取款和余额查询等行为,执行主函数测试。要求实现银行账户类,包含户名、账号以及当前余额属性。
时间: 2025-06-09 07:01:52 浏览: 69
要设计一个简单的银行账户系统,我们可以创建一个`BankAccount`类,它包含三个私有成员变量:户名(`name_`)、账号(`accountNumber_`)和当前余额(`balance_`)。这个类还会定义一些公共的方法,如`openAccount()`用于开户,`deposit()`用于存款,`withdraw()`用于取款,以及`checkBalance()`用于查询余额。以下是完整的C++代码示例:
```cpp
#include <iostream>
#include <string>
class BankAccount {
private:
std::string name_; // 户名
std::string accountNumber; // 账号
double balance_; // 当前余额
public:
// 构造函数,初始化户名和初始余额为0
BankAccount(const std::string& name) : name_(name), balance_(0) {}
// 打开新账户,设置初始余额
void openAccount(double initialBalance = 0) {
if (initialBalance >= 0) {
balance_ = initialBalance;
} else {
std::cout << "Invalid initial balance, setting to 0." << std::endl;
balance_ = 0;
}
}
// 存款
void deposit(double amount) {
if (amount >= 0) {
balance_ += amount;
std::cout << "Deposited $" << amount << ". New balance is $" << balance_ << "." << std::endl;
} else {
std::cout << "Invalid deposit amount, ignored." << std::endl;
}
}
// 取款
bool withdraw(double amount) {
if (amount <= balance_) {
balance_ -= amount;
std::cout << "Withdrawn $" << amount << ". New balance is $" << balance_ << "." << std::endl;
return true;
} else {
std::cout << "Insufficient funds, transaction failed." << std::endl;
return false;
}
}
// 查询余额
double checkBalance() const {
return balance_;
}
// 虚拟的析构函数,防止内存泄漏
virtual ~BankAccount() {}
};
int main() {
// 创建银行账户实例并进行操作
BankAccount customer("John Doe");
customer.openAccount(500); // 开户500元
customer.deposit(200); // 再存入200元
customer.withdraw(150); // 取出150元
// 检查余额
double currentBalance = customer.checkBalance();
std::cout << "Current balance: $" << currentBalance << std::endl;
return 0;
}
```
阅读全文
相关推荐



















