我有一张包含两种不同物品的地图:存款帐户和支票帐户。我想写一个汇款方法,只在两个支票账户之间转账。有没有办法检查两个帐号是否属于同一个支票帐户对象?
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;
}
答案 0 :(得分:0)
正如Shaktal says那样,您只需比较一下帐号即可。
您的代码中需要清理几件事情:
map
中有2个值可以使用相同的密钥。情况并非如此,此代码将导致Key 13映射到仅 a DepositAccount
:m_accountList[13] = CheckingAccount();
m_accountList[13] = DepositAccount();
auto
声明您的变量,特别是代替map<long, account*>::iterator
,除了更容易阅读之外,您不必在更改m_accountList
时更改回来编辑逻辑39; s类型,有关auto
的更多信息,我相信最终文章是:https://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/ 进行这些更正后,您的代码应如下所示:
bool Bank::moneyTransfer(long fromAccount, long toAccount, double amount)
{
if(fromAccount != toAccount) {
auto iterFrom = m_accountList.find(fromAccount);
if (iterFrom != m_accountList.end()) {
auto iterTo = m_account.find(toAccount);
if (iterFrom != m_accountList.end() && iterFrom->second->drawMoney(amount)) {
iterTo->second->payIn(amount);
return true;
}
}
}
return false;
}