设计一个基本帐户类,通过继承设计一个储蓄 帐户类。在储蓄帐户类中增加一个静态成员变 量年利率,并增加成员函数: (1)计算月利息; (2)更改年利率。 编写主程序进行测试,
时间: 2024-05-14 14:12:30 浏览: 38
基本账户类:
```cpp
class Account {
protected:
double balance; // 账户余额
public:
Account(double balance = 0) {
this->balance = balance;
}
double getBalance() const {
return balance;
}
void deposit(double amount) { // 存款
balance += amount;
}
virtual bool withdraw(double amount) { // 取款
if (balance < amount) return false;
balance -= amount;
return true;
}
};
```
储蓄账户类:
```cpp
class SavingsAccount : public Account {
private:
static double annualInterestRate; // 年利率
public:
SavingsAccount(double balance = 0) : Account(balance) {}
double calculateInterest() { // 计算月利息
return balance * (annualInterestRate / 12);
}
static void modifyInterestRate(double rate) { // 修改年利率
annualInterestRate = rate;
}
};
double SavingsAccount::annualInterestRate = 0.01; // 初始化年利率为1%
int main() {
SavingsAccount sa(1000);
cout << sa.getBalance() << endl; // 输出账户余额
sa.deposit(500);
cout << sa.getBalance() << endl; // 存款后余额
sa.withdraw(200);
cout << sa.getBalance() << endl; // 取款后余额
cout << sa.calculateInterest() << endl; // 计算月利息
SavingsAccount::modifyInterestRate(0.02); // 修改年利率为2%
cout << sa.calculateInterest() << endl; // 计算月利息
return 0;
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)