【问题标题】:check if a value belongs to a certain object检查一个值是否属于某个对象
【发布时间】: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 来确保帐户是否属于特定类型,如果您有多态类。
  • 为了能够回答这个问题,我们需要知道Kontoaccount 是如何定义的,正如@JoachimPileborg 所写:如果存在某种多态性。

标签: c++ dictionary key equality


【解决方案1】:

问。有没有办法检查两个帐号是否属于同一个支票账户对象?

A.是的

作为Shaktal says,您传递的帐号只是比较它们。

您的代码中有几件事需要清理:

  1. 您提出这个问题的事实表明您认为您可以在 map 中拥有相同的 Key 和 2 个值。情况并非如此,此代码将导致 Key 13 映射到 DepositAccount
m_accountList[13] = CheckingAccount();
m_accountList[13] = DepositAccount();
  1. 请使用auto 来声明您的变量,尤其是代替map&lt;long, account*&gt;::iterator,除了更易于阅读之外,当您更改m_accountList 的类型时,您不必返回并编辑您的逻辑,以获取更多信息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;
}  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 2011-02-05
    • 2012-12-22
    • 2017-10-21
    • 1970-01-01
    相关资源
    最近更新 更多