请用c++写出根据教材17.6节中所定义的Account类、Savings类和Checking类,编写一个应用程序,它读入一系列账号的存款。创建若干储蓄和结算账户,并输出所有账号的存款数据。 (假设账号中初始存款均为0) 账号类型:S表示Savings账户,C表示Checking账户。 输入 存款笔数N 以下每行数据为每笔存款账号的数据。格式为:类型 账号 金额 输出 每行输出一笔账号和对应存款金额数。 样例输入 3 S 20201001 200 C 20201003 500 S 20201007 1000 样例输出 20201001 200 20201003 500 20201007 1000 提示 数据之间为空格 要求用动态内存分配,函数解决问题。
时间: 2023-06-15 17:07:36 浏览: 350
以下是代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Account {
protected:
string accountNumber;
double balance;
public:
Account(string accountNumber = "", double balance = 0.0) {
this->accountNumber = accountNumber;
this->balance = balance;
}
virtual void deposit(double amount) {};
virtual void display() {
cout << accountNumber << " " << balance << endl;
}
virtual ~Account() {}
};
class Savings : public Account {
public:
Savings(string accountNumber = "", double balance = 0.0) : Account(accountNumber, balance) {}
void deposit(double amount) {
balance += amount;
}
void display() {
cout << accountNumber << " " << balance << endl;
}
};
class Checking : public Account {
public:
Checking(string accountNumber = "", double balance = 0.0) : Account(accountNumber, balance) {}
void deposit(double amount) {
balance += amount;
}
void display() {
cout << accountNumber << " " << balance << endl;
}
};
int main() {
int n;
cin >> n;
Account **accounts = new Account *[n];
for (int i = 0; i < n; i++) {
char type;
string accountNumber;
double balance;
cin >> type >> accountNumber >> balance;
if (type == 'S') {
accounts[i] = new Savings(accountNumber, balance);
}
else if (type == 'C') {
accounts[i] = new Checking(accountNumber, balance);
}
accounts[i]->deposit(balance);
}
for (int i = 0; i < n; i++) {
accounts[i]->display();
delete accounts[i];
}
delete[] accounts;
return 0;
}
```
输入格式为存款笔数和每笔存款的账号类型、账号和金额,输出格式为每行输出一个账号和对应存款金额数。程序首先读入存款笔数,然后使用动态内存分配创建若干个账户对象(根据账号类型创建 Savings 或 Checking 类的对象),并累加每个账户的存款金额。最后遍历所有账户对象并输出账户号码和存款金额。注意,每个账户对象都需要使用 delete 进行释放。
阅读全文