gpt4 book ai didi

c++ - 重载比较运算符不工作

转载 作者:行者123 更新时间:2023-11-28 03:30:48 25 4
gpt4 key购买 nike

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

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

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

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

谢谢。

最佳答案

你的条件是错误的:

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

关于c++ - 重载比较运算符不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12688768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com