【发布时间】: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->next:) ? -
确保将 countA 和 countB 初始化为 0。这可能是问题的根源。
-
在调试器中单步执行会告诉你。
标签: c++ linked-list operator-overloading