【问题标题】:Overloaded > operator returns true when it should be returning false重载 > 运算符在应该返回 false 时返回 true
【发布时间】:2015-05-19 20:15:18
【问题描述】:

我试图重载 > 运算符,以便我可以看到哪个 Polynomial 对象在多项式中有多少项方面更大(例如 - 如果 Polynomial1 有 4 个项,Polynomial2 有 3 个项,Polynomial1 > Polynomial2 将返回是的。我的多项式对象是链表,所以我想我会遍历每个列表并为每个列表创建一个计数器变量。对于遇到的每个节点(项),计数器将加 1。但是,当我在main,它对项数相等的列表返回 True。

bool Polynomial::operator>(const Polynomial &other ) const
{
    int countA;
    int countB;
    shared_ptr<Polynomial::Term> a = this->head;
    shared_ptr<Polynomial::Term> b = other.head;

    for(a; a!=nullptr; a = a->next)
    {
        countA++;
    }
    for(b; b!=nullptr; b = a=b->next)
    {
        countB++;
    }
    if(countA > countB)
    {
        cout << "Greater then" << endl;
        return true;
    }
    else
    {
        cout << "less then or equal to" << endl;
        return false;
    }
}

【问题讨论】:

  • b = a=b-&gt;next :) ?
  • 确保将 countA 和 countB 初始化为 0。这可能是问题的根源。
  • 在调试器中单步执行会告诉你。

标签: c++ linked-list operator-overloading


【解决方案1】:

永远不要忘记初始化:)

int countA = 0;
int countB = 0;

【讨论】:

    【解决方案2】:

    您需要将countAcountB 初始化为零。

    【讨论】:

      【解决方案3】:

      您的错误出现在第二个 for 循环中。 b = a = b->下一个。它应该是 b = b->next。

      【讨论】:

      • 虽然很奇怪,但这不是问题所在。对b有同样的效果,而且a的虚假值永远不会被使用。
      • @developmentFun 谢谢。我不敢相信我忘了初始化它们。
      猜你喜欢
      • 1970-01-01
      • 2012-06-20
      • 2019-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 2023-03-26
      相关资源
      最近更新 更多