【发布时间】:2016-11-01 00:21:24
【问题描述】:
我有一张包含两种不同对象的地图:存款账户和支票账户。我想写一个转账方法,只在两个支票账户之间转账。有没有办法检查两个帐号是否属于同一个支票账户对象?
bool Bank::moneyTransfer(long fromAccount,long toAccount, double amount)
{
map<long, account*>::iterator iterFrom;
map<long, account*>::iterator iterTo;
iterFrom = m_accountList.find(fromAccount);
if (iterFrom == m_accountList.end()) {
return false;
}
iterTo = m_account.find(toAccount);
if (iterFrom == m_accountList.end()) {
return false;
}
Konto *fromAccount = iterFrom->second;
Konto *toAccount = iterTo->second;
if (!fromAccount->drawMoney(amount)) {
return false;
}
toAccount->payIn(amount);
return true;
}
【问题讨论】:
-
在你的逻辑中,这两个帐号会不会简单地相同(即
fromAccount == toAccount)? -
您可以使用
dynamic_cast来确保帐户是否属于特定类型,如果您有多态类。 -
为了能够回答这个问题,我们需要知道
Konto和account是如何定义的,正如@JoachimPileborg 所写:如果存在某种多态性。
标签: c++ dictionary key equality