在c++中用纯虚函数和多态实现银行账户管理系统设计
时间: 2024-05-24 22:13:57 浏览: 19
很高兴能够为您解答问题。在 C 中,实现银行账户管理系统可以使用纯虚函数和多态。下面是一个示例代码:
#include <stdio.h>
typedef struct Account Account;
struct Account {
const char* name;
double balance;
void (*deposit)(Account* this, double amount);
void (*withdraw)(Account* this, double amount);
};
void account_deposit(Account* this, double amount) {
this->balance += amount;
printf("Deposited %.2f. New balance is %.2f.\n", amount, this->balance);
}
void account_withdraw(Account* this, double amount) {
if (amount > this->balance) {
printf("Insufficient balance.\n");
return;
}
this->balance -= amount;
printf("Withdrawn %.2f. New balance is %.2f.\n", amount, this->balance);
}
void init_account(Account* acc, const char* name, double balance) {
acc->name = name;
acc->balance = balance;
acc->deposit = account_deposit;
acc->withdraw = account_withdraw;
}
int main() {
Account savings, checking;
init_account(&savings, "Savings", 5000.0);
init_account(&checking, "Checking", 2000.0);
Account* accounts[] = {&savings, &checking};
for (int i = 0; i < sizeof(accounts) / sizeof(Account*); i++) {
Account* acc = accounts[i];
printf("%s balance: %.2f.\n", acc->name, acc->balance);
acc->deposit(acc, 100.0);
acc->withdraw(acc, 50.0);
}
return 0;
}
在这个示例中,我们定义了一个 Account 结构体,它包含账户名称和余额。我们还定义了两个纯虚函数 deposit 和 withdraw,这些函数可以通过指向该函数指针的方式在 Account 结构体中实现。init_account 函数初始化 Account 结构体,将指向正确 deposit 和 withdraw 函数的函数指针设置为结构体中的函数。最后,我们可以使用 init_account 函数创建两个 Account 对象并对它们进行操作,而无需知道它们如何实现。
希望这可以帮助您设计您的银行账户管理系统。
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)