0

我正在尝试比较我的类 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
    }

好的,这是程序中包含的重载 operator<,在通用对象上测试它会得到预期的结果:

    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;
       }

我对编程很陌生,所以我很欣赏任何回应,尤其是风格批评,因为我还在学习。我的逻辑是错误的,还是我需要注意其他规则?我不完全理解为什么我的参数是引用的,或者我是否真的需要取消引用参数来调用运算符。

谢谢。

4

1 回答 1

2

你的条件不对:

if (strcmp(op2.lastName, lastName))

对于不同的字符串,无论它们的顺序如何,这将返回 not- false(true),并且您的函数将返回false

正确的条件是:

if (strcmp(op2.lastName, lastName) >= 0)

或者你可以重写整个事情:

bool CustomerNode::operator< (const CustomerNode& op2) const
{
   return  strcmp(op2.lastName, lastName) < 0;
}
于 2012-10-02T10:39:08.147 回答