我试图比较我的类CustomerNode的两个对象,然后返回与这些方法的字母优势相关的结果。我无法弄清楚为什么这不起作用。对我来说,逻辑似乎很好,我遵循我的作业中的指示。
bool OrderedList::add (CustomerNode* newEntry)
{
if (newEntry != 0)
{
CustomerNode * current;
CustomerNode * previous = NULL;
if(!head)
head = newEntry;
current = head;
// initialize "current" & "previous" pointers for list traversal
while(current && *newEntry < *current) // location not yet found (use short-circuit evaluation)
{
// move on to next location to check
previous = current;
current = current->getNext();
}
// insert node at found location (2 cases: at head or not at head)
//if previous did not acquire a value, then the newEntry was
//superior to the first in the list.
if(previous == NULL)
head = newEntry;
else
{
previous->setNext(newEntry); //Previous now needs to point to the newEntry
newEntry->setNext(current); //and the newEntry points to the value stored in current.
}
}
return newEntry != 0; // success or failure
}
好的,这是重载运算符&lt;包含在程序中,在通用对象上测试它会产生预期的结果:
bool CustomerNode::operator< (const CustomerNode& op2) const
{
bool result = true;
//Variable to carry & return result
//Initialize to true, and then:
if (strcmp(op2.lastName, lastName))
result = false;
return result;
}
我对编程非常陌生,所以我很欣赏任何回复,尤其是风格批评,因为我还在学习。我的逻辑是错误的,还是我需要注意其他规则?我不完全理解为什么我的参数是引用,或者我实际上需要取消引用参数来调用操作符。
感谢。
答案 0 :(得分:2)
你的情况错了:
if (strcmp(op2.lastName, lastName))
对于不同的字符串,无论其顺序如何,都不会返回 - false
(true),并且您的函数将返回false
。
正确的条件是:
if (strcmp(op2.lastName, lastName) >= 0)
或者你可以重写整件事:
bool CustomerNode::operator< (const CustomerNode& op2) const
{
return strcmp(op2.lastName, lastName) < 0;
}