我有四个班,银行,帐户,保存和检查.保存和检查都是从Account公开继承的.我在Account中有两个虚拟空函数; 存款和取款.我只发布了存款存款功能的代码,因为其余代码的问题是重复的.
我的Bank类中有一个函数,它将一个帐户添加到account类型的向量中.每当我为存储对象调用存款函数时,它使用Account的存款功能而不是保存(使用调试器找到).
起初我没有使用指针,但我经历了这个线程:多态性误解/重新定义的虚函数无法正常工作并学习使用指针来实现虚函数.
问题:什么导致我的代码使用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();
};
Run Code Online (Sandbox Code Playgroud)
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;
};
Run Code Online (Sandbox Code Playgroud)
Bank.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);
}
Run Code Online (Sandbox Code Playgroud)
我没有看到执行此操作的代码,但问题是说它Bank有一个帐户向量,即std::vector<account>.如果是这种情况,问题是派生类对象account在被推入向量时会被切成对象,并且它们会失去派生的对象.代码需要使用指针或引用account.通常,这是使用std::vector<account*>或std::vector<std::unique_ptr<account>>分配的派生对象完成的new.代码还应该传递account由指针或引用派生的类型的对象,而不是通过值(例如,void Bank::addAccount(Account a)因为它将对它所调用的参数进行切片而不起作用).
| 归档时间: |
|
| 查看次数: |
287 次 |
| 最近记录: |