我有四个班级,银行,帐户,储蓄和支票。保存和检查都是从帐户公开继承的。我的帐户中有两个虚拟虚函数:存款和取款。我只发布用于保存存款功能的代码,因为该问题对于其余代码都是重复的。
我的Bank类中有一个函数,该函数会将一个帐户添加到类型为account的向量中。每当我为储蓄对象调用存款功能时,它都会使用Account的存款功能而不是Saving(使用调试器找到)。
最初,我没有使用指针,但是我经历了这个线程:多态性误解/重新定义的虚拟函数无法正常工作,并学会了将指针用于虚拟函数。
问题:是什么导致我的代码使用Account.cpp中的默认虚拟方法,而不是Saving.cpp中的预期“多态”方法?我该如何解决?
Account.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();
};
Saving.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;
};
银行
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);
}
我看不到执行此操作的代码,但问题是该帐户Bank
具有一个向量,即std::vector<account>
。在这种情况下,问题在于派生类对象account
在被推入向量时会被切成对象,并且失去其派生性。该代码需要使用的指针或引用account
。通常,这是通过std::vector<account*>
或std::vector<std::unique_ptr<account>>
分配的派生对象完成的new
。该代码还应传递account
由指针或引用派生的类型的对象,而不是按值传递的对象(例如,void Bank::addAccount(Account a)
将对其进行调用的参数进行切片,因此将不起作用)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句