C++ 脑图(三)异常、STL

1、异常

异常举例

 BankAccount.h

#ifndef BANK_ACCOUNT_H
#define BANK_ACCOUNT_H

#include <iostream>
#include <stdexcept>

class InsufficientFundsException : public std::runtime_error {
public:
    InsufficientFundsException() : std::runtime_error("Insufficient funds for this operation.") {}
};

class BankAccount {
private:
    std::string accountNumber;
    double balance;

public:
    BankAccount(const std::string& accNum) : accountNumber(accNum), balance(0.0) {}

    void deposit(double amount) {
        if (amount <= 0) {
            throw std::invalid_argument("Deposit amount must be positive.");
        }
        balance += amount;
        std::cout << "Deposited: " << amount << ", New Balance: " << balance << std::endl;
    }

    void withdraw(double amount) {
        if (amount > balance) {
            throw InsufficientFundsException();
        }
        balance -= amount;
        std::cout << "Withdrew: " << amount << ", New Balance: " << balance << std::endl;
    }

    double getBalance() const {
        return balance;
    }

    std::string getAccountNumber() const {
        return accountNumber;
    }
};

#endif // BANK_ACCOUNT_H

  Bank.h

#ifndef BANK_H
#define BANK_H

#include <iostream>
#include <map>
#include "BankAccount.h"

class AccountNotFoundException : public std::runtime_error {
public:
    AccountNotFoundException(const std::string& accNum) 
        : std::runtime_error("Account not found: " + accNum) {}
};

class Bank {
private:
    std::map<std::string, BankAccount> accounts;

public:
    void createAccount(const std::string& accNum) {
        accounts.emplace(accNum, BankAccount(accNum));
        std::cout << "Account created: " << accNum << std::endl;
    }

    BankAccount& getAccount(const std::string& accNu
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值