首页 > 后端开发 > C++ > 正文

怎样用C++制作简易银行账户系统 类与对象的基础应用

P粉602998670
发布: 2025-08-02 12:53:01
原创
317人浏览过

如何利用c++++的类与对象模拟银行账户的基本操作并构建管理系统?1. 定义bankaccount类,包含账户id、持有人姓名和余额等属性,并实现存款、取款、查询余额及打印账户信息的方法;2. 创建bank类,使用std::vector容器管理多个bankaccount对象,提供添加、删除、查找账户等功能;3. 为处理并发访问,引入std::mutex互斥锁保护balance变量,确保线程安全;4. 扩展支持不同账户类型时,使用继承机制设计savingsaccount(储蓄账户)和checkingaccount(支票账户),分别实现利率计算和透支功能;5. 实现账户数据持久化,可通过文件存储使用ofstream和ifstream进行读写操作,或通过数据库如sqlite实现更复杂的数据管理。

怎样用C++制作简易银行账户系统 类与对象的基础应用

核心在于如何利用C++的类与对象,模拟银行账户的创建、存取款等基本操作,构建一个简单的银行账户管理系统。

怎样用C++制作简易银行账户系统 类与对象的基础应用

解决方案:

首先,我们需要定义一个

BankAccount
登录后复制
类,它将包含账户的基本属性,如账户ID、账户持有人姓名和账户余额,以及相关的操作方法。

立即学习C++免费学习笔记(深入)”;

怎样用C++制作简易银行账户系统 类与对象的基础应用
#include <iostream>
#include <string>

class BankAccount {
private:
    int accountID;
    std::string accountHolderName;
    double balance;

public:
    // 构造函数
    BankAccount(int id, std::string name, double initialBalance) : accountID(id), accountHolderName(name), balance(initialBalance) {}

    // 获取账户ID
    int getAccountID() const {
        return accountID;
    }

    // 获取账户持有人姓名
    std::string getAccountHolderName() const {
        return accountHolderName;
    }

    // 获取账户余额
    double getBalance() const {
        return balance;
    }

    // 存款
    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            std::cout << "存款成功,当前余额:" << balance << std::endl;
        } else {
            std::cout << "存款金额必须大于0" << std::endl;
        }
    }

    // 取款
    void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            std::cout << "取款成功,当前余额:" << balance << std::endl;
        } else {
            std::cout << "取款失败,余额不足或取款金额无效" << std::endl;
        }
    }

    // 打印账户信息
    void printAccountInfo() const {
        std::cout << "账户ID: " << accountID << std::endl;
        std::cout << "账户持有人姓名: " << accountHolderName << std::endl;
        std::cout << "账户余额: " << balance << std::endl;
    }
};

int main() {
    // 创建一个银行账户对象
    BankAccount account1(12345, "张三", 1000.0);

    // 打印账户信息
    account1.printAccountInfo();

    // 存款
    account1.deposit(500.0);

    // 取款
    account1.withdraw(200.0);

    // 再次打印账户信息
    account1.printAccountInfo();

    return 0;
}
登录后复制

这个简单的例子展示了如何创建一个

BankAccount
登录后复制
类,并实现存款和取款功能。 接下来,可以考虑如何扩展这个系统,例如添加账户管理功能,允许多个账户存在。

如何添加账户管理功能,实现多个账户的管理?

怎样用C++制作简易银行账户系统 类与对象的基础应用

创建一个

Bank
登录后复制
类,该类包含一个
BankAccount
登录后复制
对象的容器(例如
std::vector
登录后复制
),并提供添加账户、删除账户、查找账户等功能。

#include <iostream>
#include <string>
#include <vector>

// BankAccount 类 (如上所示)

class Bank {
private:
    std::vector<BankAccount> accounts;

public:
    // 添加账户
    void addAccount(const BankAccount& account) {
        accounts.push_back(account);
        std::cout << "账户已添加" << std::endl;
    }

    // 删除账户 (根据账户ID)
    void removeAccount(int accountID) {
        for (auto it = accounts.begin(); it != accounts.end(); ++it) {
            if (it->getAccountID() == accountID) {
                accounts.erase(it);
                std::cout << "账户已删除" << std::endl;
                return;
            }
        }
        std::cout << "未找到该账户" << std::endl;
    }

    // 查找账户 (根据账户ID)
    BankAccount* findAccount(int accountID) {
        for (auto& account : accounts) {
            if (account.getAccountID() == accountID) {
                return &account;
            }
        }
        std::cout << "未找到该账户" << std::endl;
        return nullptr;
    }

    // 打印所有账户信息
    void printAllAccounts() const {
        if (accounts.empty()) {
            std::cout << "银行中没有账户" << std::endl;
            return;
        }
        for (const auto& account : accounts) {
            account.printAccountInfo();
            std::cout << "---------------------" << std::endl;
        }
    }
};

int main() {
    Bank myBank;

    // 创建账户
    BankAccount account1(12345, "张三", 1000.0);
    BankAccount account2(67890, "李四", 500.0);

    // 添加账户到银行
    myBank.addAccount(account1);
    myBank.addAccount(account2);

    // 打印所有账户信息
    myBank.printAllAccounts();

    // 查找账户
    BankAccount* foundAccount = myBank.findAccount(12345);
    if (foundAccount != nullptr) {
        std::cout << "找到账户:" << foundAccount->getAccountHolderName() << std::endl;
    }

    // 删除账户
    myBank.removeAccount(67890);

    // 再次打印所有账户信息
    myBank.printAllAccounts();

    return 0;
}
登录后复制

这个

Bank
登录后复制
类维护了一个
BankAccount
登录后复制
的容器,并提供了添加、删除和查找账户的功能。 值得注意的是,错误处理和边界情况的处理非常重要,例如,当尝试删除或查找不存在的账户时,应该给出明确的提示。

如何处理并发访问银行账户时的线程安全问题?

当多个线程同时访问和修改银行账户余额时,可能会出现数据竞争,导致账户余额错误。 为了解决这个问题,可以使用互斥锁(

std::mutex
登录后复制
)来保护对账户余额的访问。

#include <iostream>
#include <string>
#include <mutex>
#include <thread>

class BankAccount {
private:
    int accountID;
    std::string accountHolderName;
    double balance;
    std::mutex balanceMutex; // 互斥锁

public:
    BankAccount(int id, std::string name, double initialBalance) : accountID(id), accountHolderName(name), balance(initialBalance) {}

    int getAccountID() const {
        return accountID;
    }

    std::string getAccountHolderName() const {
        return accountHolderName;
    }

    double getBalance() const {
        std::lock_guard<std::mutex> lock(balanceMutex); // 获取锁
        return balance;
    }

    void deposit(double amount) {
        if (amount > 0) {
            std::lock_guard<std::mutex> lock(balanceMutex); // 获取锁
            balance += amount;
            std::cout << "存款成功,当前余额:" << balance << " (线程ID: " << std::this_thread::get_id() << ")" << std::endl;
        } else {
            std::cout << "存款金额必须大于0" << std::endl;
        }
    }

    void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            std::lock_guard<std::mutex> lock(balanceMutex); // 获取锁
            balance -= amount;
            std::cout << "取款成功,当前余额:" << balance << " (线程ID: " << std::this_thread::get_id() << ")" << std::endl;
        } else {
            std::cout << "取款失败,余额不足或取款金额无效" << std::endl;
        }
    }

    void printAccountInfo() const {
        std::lock_guard<std::mutex> lock(balanceMutex); // 获取锁
        std::cout << "账户ID: " << accountID << std::endl;
        std::cout << "账户持有人姓名: " << accountHolderName << std::endl;
        std::cout << "账户余额: " << balance << std::endl;
    }
};

void performTransactions(BankAccount& account, int numTransactions) {
    for (int i = 0; i < numTransactions; ++i) {
        account.deposit(100.0);
        account.withdraw(50.0);
    }
}

int main() {
    BankAccount account(12345, "张三", 1000.0);

    // 创建多个线程进行并发操作
    std::thread thread1(performTransactions, std::ref(account), 1000);
    std::thread thread2(performTransactions, std::ref(account), 1000);

    // 等待线程完成
    thread1.join();
    thread2.join();

    // 打印最终账户信息
    account.printAccountInfo();

    return 0;
}
登录后复制

在这个例子中,

std::mutex balanceMutex
登录后复制
用于保护
balance
登录后复制
变量。
std::lock_guard
登录后复制
是一个RAII(Resource Acquisition Is Initialization)风格的锁,它在构造时获取锁,在析构时释放锁,确保在任何情况下都能正确释放锁,即使发生异常。 通过使用互斥锁,可以避免多个线程同时修改
balance
登录后复制
变量,从而保证线程安全。

Linfo.ai
Linfo.ai

Linfo AI 是一款AI驱动的 Chrome 扩展程序,可以将网页文章、行业报告、YouTube 视频和 PDF 文档转换为结构化摘要。

Linfo.ai 104
查看详情 Linfo.ai

如何扩展银行账户系统,支持不同类型的账户(例如储蓄账户和支票账户)?

可以使用继承来实现不同类型的账户。 创建一个基类

BankAccount
登录后复制
,然后创建派生类
SavingsAccount
登录后复制
(储蓄账户)和
CheckingAccount
登录后复制
(支票账户),它们继承自
BankAccount
登录后复制
并添加特定于账户类型的属性和方法。

#include <iostream>
#include <string>

class BankAccount {
protected: // 修改为protected,允许派生类访问
    int accountID;
    std::string accountHolderName;
    double balance;

public:
    BankAccount(int id, std::string name, double initialBalance) : accountID(id), accountHolderName(name), balance(initialBalance) {}

    virtual ~BankAccount() {} // 虚析构函数

    int getAccountID() const {
        return accountID;
    }

    std::string getAccountHolderName() const {
        return accountHolderName;
    }

    double getBalance() const {
        return balance;
    }

    virtual void deposit(double amount) { // 虚函数
        if (amount > 0) {
            balance += amount;
            std::cout << "存款成功,当前余额:" << balance << std::endl;
        } else {
            std::cout << "存款金额必须大于0" << std::endl;
        }
    }

    virtual void withdraw(double amount) { // 虚函数
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            std::cout << "取款成功,当前余额:" << balance << std::endl;
        } else {
            std::cout << "取款失败,余额不足或取款金额无效" << std::endl;
        }
    }

    virtual void printAccountInfo() const { // 虚函数
        std::cout << "账户ID: " << accountID << std::endl;
        std::cout << "账户持有人姓名: " << accountHolderName << std::endl;
        std::cout << "账户余额: " << balance << std::endl;
    }
};

class SavingsAccount : public BankAccount {
private:
    double interestRate;

public:
    SavingsAccount(int id, std::string name, double initialBalance, double rate) : BankAccount(id, name, initialBalance), interestRate(rate) {}

    void addInterest() {
        double interest = balance * interestRate;
        deposit(interest);
        std::cout << "已添加利息:" << interest << std::endl;
    }

    void printAccountInfo() const override { // 重写
        BankAccount::printAccountInfo();
        std::cout << "利率: " << interestRate << std::endl;
    }
};

class CheckingAccount : public BankAccount {
private:
    double overdraftLimit;

public:
    CheckingAccount(int id, std::string name, double initialBalance, double limit) : BankAccount(id, name, initialBalance), overdraftLimit(limit) {}

    void withdraw(double amount) override { // 重写
        if (amount > 0 && (balance + overdraftLimit) >= amount) {
            balance -= amount;
            std::cout << "取款成功,当前余额:" << balance << std::endl;
        } else {
            std::cout << "取款失败,超过透支额度或取款金额无效" << std::endl;
        }
    }

    void printAccountInfo() const override { // 重写
        BankAccount::printAccountInfo();
        std::cout << "透支额度: " << overdraftLimit << std::endl;
    }
};

int main() {
    SavingsAccount savingsAccount(11111, "王五", 2000.0, 0.05);
    CheckingAccount checkingAccount(22222, "赵六", 1500.0, 500.0);

    savingsAccount.printAccountInfo();
    savingsAccount.addInterest();
    savingsAccount.printAccountInfo();

    checkingAccount.printAccountInfo();
    checkingAccount.withdraw(2000.0); // 允许透支
    checkingAccount.printAccountInfo();

    return 0;
}
登录后复制

在这个例子中,

SavingsAccount
登录后复制
添加了
interestRate
登录后复制
属性和
addInterest
登录后复制
方法,而
CheckingAccount
登录后复制
添加了
overdraftLimit
登录后复制
属性并重写了
withdraw
登录后复制
方法以支持透支。
virtual
登录后复制
关键字使得基类的方法可以被派生类重写,从而实现多态性。

如何将账户数据持久化到文件或数据库中?

可以使用文件或数据库来持久化账户数据。 对于简单的系统,可以使用文件存储。 对于更复杂的系统,可以使用数据库(例如SQLite、MySQL或PostgreSQL)。

使用文件存储:

#include <iostream>
#include <fstream>
#include <string>

class BankAccount {
private:
    int accountID;
    std::string accountHolderName;
    double balance;

public:
    BankAccount(int id, std::string name, double initialBalance) : accountID(id), accountHolderName(name), balance(initialBalance) {}

    int getAccountID() const {
        return accountID;
    }

    std::string getAccountHolderName() const {
        return accountHolderName;
    }

    double getBalance() const {
        return balance;
    }

    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            std::cout << "存款成功,当前余额:" << balance << std::endl;
        } else {
            std::cout << "存款金额必须大于0" << std::endl;
        }
    }

    void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            std::cout << "取款成功,当前余额:" << balance << std::endl;
        } else {
            std::cout << "取款失败,余额不足或取款金额无效" << std::endl;
        }
    }

    void printAccountInfo() const {
        std::cout << "账户ID: " << accountID << std::endl;
        std::cout << "账户持有人姓名: " << accountHolderName << std::endl;
        std::cout << "账户余额: " << balance << std::endl;
    }

    // 将账户数据保存到文件
    void saveToFile(std::ofstream& file) const {
        file << accountID << std::endl;
        file << accountHolderName << std::endl;
        file << balance << std::endl;
    }

    // 从文件加载账户数据
    void loadFromFile(std::ifstream& file) {
        file >> accountID;
        file.ignore(); // 忽略换行符
        std::getline(file, accountHolderName);
        file >> balance;
        file.ignore(); // 忽略换行符
    }
};

int main() {
    BankAccount account1(12345, "张三", 1000.0);

    // 保存账户到文件
    std::ofstream outFile("accounts.txt");
    if (outFile.is_open()) {
        account1.saveToFile(outFile);
        outFile.close();
        std::cout << "账户已保存到文件" << std::endl;
    } else {
        std::cerr << "无法打开文件进行写入" << std::endl;
    }

    // 从文件加载账户
    BankAccount account2(0, "", 0.0); // 创建一个空账户
    std::ifstream inFile("accounts.txt");
    if (inFile.is_open()) {
        account2.loadFromFile(inFile);
        inFile.close();
        std::cout << "账户已从文件加载" << std::endl;
        account2.printAccountInfo();
    } else {
        std::cerr << "无法打开文件进行读取" << std::endl;
    }

    return 0;
}
登录后复制

这个例子展示了如何使用

ofstream
登录后复制
ifstream
登录后复制
将账户数据保存到文件和从文件加载账户数据。 需要注意的是,文件格式需要仔细设计,以确保数据的正确读取和写入。 此外,还需要处理文件打开失败等错误情况。

使用数据库存储:

使用数据库需要引入相应的数据库库,例如SQLite的

sqlite3
登录后复制
库。 这里只提供一个概念性的示例,具体的实现需要根据选择的数据库和库进行调整。

// (伪代码,需要引入数据库库)
/*
#include <sqlite3.h>

int main() {
    sqlite3 *db;
    int rc = sqlite3_open("bank.db", &db);

    if (rc) {
        std::cerr << "无法打开数据库: " << sqlite3_errmsg(db) << std::endl;
        return 1;
    }

    // 创建表
    const char *createTableSQL = "CREATE TABLE IF NOT EXISTS accounts ("
                                  "accountID INTEGER PRIMARY KEY,"
                                  "accountHolderName TEXT,"
                                  "balance REAL);";

    rc = sqlite3_exec(db, createTableSQL, 0, 0, 0);
    if (rc != SQLITE_OK) {
        std::cerr << "创建表失败: " << sqlite3_errmsg(db) << std::endl;
        sqlite3_close(db);
        return 1;
    }

    // 插入数据
    const char *insertSQL = "INSERT INTO accounts (accountID, accountHolderName, balance) VALUES (12345, '张三', 1000.0);";
    rc = sqlite3_exec(db, insertSQL, 0, 0, 0);
    if (rc != SQLITE_OK) {
        std::cerr << "插入数据失败: " << sqlite3_errmsg(db) << std::endl;
        sqlite3_close(db);
        return 1;
    }

    // 查询数据
    const char *selectSQL = "SELECT * FROM accounts;";
    sqlite3_stmt *stmt;
    rc = sqlite3_prepare_v2(db, selectSQL, -1, &stmt, 0);
    if (rc != SQLITE_OK) {
        std::cerr << "查询失败: " << sqlite3_errmsg(db) << std::endl;
        sqlite3_close(db);
        return 1;
    }

    while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
        int accountID = sqlite3_column_int(stmt, 0);
        const char *accountHolderName = (const char*)sqlite3_column_text(stmt, 1);
        double balance = sqlite3_column_double(stmt, 2);

        std::cout << "账户ID: " << accountID << std::endl;
        std::cout << "账户持有人姓名: " << accountHolderName << std::endl;
        std::cout << "账户余额: " << balance << std::endl;
    }

    sqlite3_finalize(stmt);
    sqlite3_close(db);

    return 0;
}
*/
登录后复制

这个伪代码展示了如何使用SQLite数据库存储账户数据。 你需要安装SQLite库,并根据实际情况调整代码。 使用数据库可以提供更好的数据管理和查询功能,但也增加了系统的复杂性。

以上就是怎样用C++制作简易银行账户系统 类与对象的基础应用的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号