设计一个类Account对银行客户账户进行管理Account类有数据成员balance表示账户余额构造函数成员函数getBal获取余额取钱withdraw不计手续费 存钱deposit;从Account派生出类储蓄账户SavingAccount该账户可以根据用户存款计算利息并将利息加到余额中;从Account派生出支票账户CheckingAccount类该类改写Account类的withdraw函
基类Account的设计:
class Account { protected: double balance; // 账户余额 public: Account(double b) : balance(b) {} // 构造函数 double getBal() const { return balance; } // 获取余额 virtual void withdraw(double amt) { balance -= amt; } // 取钱 virtual void deposit(double amt) { balance += amt; } // 存钱 };
派生类SavingAccount的设计:
class SavingAccount : public Account { public: SavingAccount(double b) : Account(b) {} // 构造函数 void deposit(double amt) { // 存钱并计算利息 double interest = amt * 0.01; // 利息为存款的1% balance += amt + interest; } };
派生类CheckingAccount的设计:
class CheckingAccount : public Account { private: double fee; // 手续费 public: CheckingAccount(double b, double f) : Account(b), fee(f) {} // 构造函数 void withdraw(double amt) { // 取钱扣除手续费 balance -= amt + fee; } };
在main函数中测试三个类的功能:
int main() { Account acc(1000); acc.withdraw(200); cout << "Account balance: " << acc.getBal() << endl; // 800
SavingAccount savAcc(1000);
savAcc.deposit(200);
cout << "SavingAccount balance: " << savAcc.getBal() << endl; // 1202
CheckingAccount chkAcc(1000, 10);
chkAcc.withdraw(200);
cout << "CheckingAccount balance: " << chkAcc.getBal() << endl; // 790
return 0;
原文地址: https://www.cveoy.top/t/topic/fiHw 著作权归作者所有。请勿转载和采集!