gpt4 book ai didi

c++ - 对多态 C++ 的误解

转载 作者:太空狗 更新时间:2023-10-29 23:35:26 25 4
gpt4 key购买 nike

<分区>

我有四个类,银行、账户、储蓄和支票。 Saving 和 Checking 都是从 Account 公开继承的。我在帐户中有两个虚拟无效功能;存款和取款。我只发布 Saving deposit 函数的代码,因为该问题对于其余代码是重复的。

我的 Bank 类中有一个函数,可以将一个帐户添加到帐户类型的 vector 中。每当我为储蓄对象调用存款功能时,它都会使用账户的存款功能而不是储蓄(使用调试器找到)。

起初我没有使用指针,但我经历了这个线程:Polymorphism misunderstanding / redefined virtual function not working并学习了对虚函数使用指针。

问题是什么导致我的代码使用 Account.cpp 中的默认虚拟方法而不是 Saving.cpp 中预期的“多态”方法?我该如何解决?

账户.cpp

#pragma once
#include <string>
using std::string;
enum account_type { saving, checking };

class Account
{
public:
Account();
Account(int, account_type, double);
~Account();

virtual void deposit(double&) {};
virtual void withdraw(double&) {};
protected:
int account_number;
account_type type;
double balance;

int generateAccountNumber();
double initializeBalance();
};

保存.cpp

class Saving : public Account
{
public:
Saving();
Saving(int, account_type, double);
~Saving();

void deposit(double&) //deposits some amount into a saving account
{
if (amount < 0)
throw "Cannot withdraw an amount less than $0.00";
else if (amount > balance)
throw "Cannot withdraw an amount greater than the current balance";
else
balance -= amount;
}
private:
const double interest_rate = 0.01;
};

银行.cpp

class Bank
{
private:
vector <Account*> bank_accounts;
//ORIGINAL BEFORE FIX: vector <Account> bank_accounts;
public:
void Bank::addAccount(Account a) //adds some account to a vector
{
bank_accounts.push_back(a);
}

Account * findAccount(int acc_num) //finds the account by it's account number
{
int found = -1;
for (int y = 1; y <= (int)bank_accounts.size(); y++) {
if (acc_num == bank_accounts[y - 1].getAccountNumber())
found = y - 1;
}

if (found == -1) {
throw "\nAccount not found";
}
else
{
if (bank_accounts[found].getAccountType() == 0)
{
Account * saving = &bank_accounts[found];
return saving;
}
else if (bank_accounts[found].getAccountType() == 1)
{
Account * checking = &bank_accounts[found];
return checking;
}
}
}
}

int main()
{
Bank Swiss;
Saving s(num, type, bal); // some user values for these variables
Account * tempAccount1 = &s;
Swiss.addAccount(*tempAccount1);
Swiss.findAccount(num)->deposit(amt);
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com