结构中带有类的链表无法使布尔操作正常工作

发布于 2024-10-20 09:34:50 字数 706 浏览 1 评论 0原文

我似乎无法让 Boolean 操作像我想象的那样工作。

/////.h file

class linkD
{

  private:
struct ListNode{
    driver driver;   ////class 
    ListNode *next;
};
ListNode *head;

///.cpp file

  void linkD::deleteNode(driver d){

ListNode *nodePtr;
ListNode *previousNode;
ListNode *newNode;
newNode=new ListNode;
newNode->next=NULL;
newNode->driver=d;

if(!head)
    return;
if(head->driver==d) //the problem is right here.
{
    nodePtr=head->next;
    delete head;
    head=nodePtr;
}

head->driver==d 给出了一条红线(没有运算符“==”与这些操作数匹配

我认为这是因为 head->driver< /code> 未初始化,但我可能是错的,我不确定如何初始化它,因为它位于未初始化的结构内。

I can't seem to get Boolean operation working like I thought it works.

/////.h file

class linkD
{

  private:
struct ListNode{
    driver driver;   ////class 
    ListNode *next;
};
ListNode *head;

///.cpp file

  void linkD::deleteNode(driver d){

ListNode *nodePtr;
ListNode *previousNode;
ListNode *newNode;
newNode=new ListNode;
newNode->next=NULL;
newNode->driver=d;

if(!head)
    return;
if(head->driver==d) //the problem is right here.
{
    nodePtr=head->next;
    delete head;
    head=nodePtr;
}

head->driver==d gives a redline (no operator "==" matches these operands)

I think it is because head->driver is uninitialized but I might be wrong and I am not sure how to initialize it since it's inside a uninitialized struct.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

荭秂 2024-10-27 09:34:50

那是因为 driver 是一个类对象。

您必须为类定义相等运算符。

您是否期望类对象像指针一样(如在 Java 中,即它们可以为 NULL)

如果您想测试驱动程序对象的相等性,请像这样定义它:

class driver
{
    public:
        bool operator==(driver const& rhs) const
        {
            return  x == rhs.x && y == rhs.y && z == rhs.z;
        }
    private:
        int x;
        int y;
        int z;
};

int test
{
     driver x;
     driver y;

     if (x == y)   // this calls x.operator==(y)
     {             // So y is the rhs parameter.
     }
}

That's because driver is a class object.

You have to define the equality operator for a class.

Are you expecting class object to be pointer like (as in Java i.e. They can be NULL)

If you want to test driver objects for equality define it like this:

class driver
{
    public:
        bool operator==(driver const& rhs) const
        {
            return  x == rhs.x && y == rhs.y && z == rhs.z;
        }
    private:
        int x;
        int y;
        int z;
};

int test
{
     driver x;
     driver y;

     if (x == y)   // this calls x.operator==(y)
     {             // So y is the rhs parameter.
     }
}
始终不够爱げ你 2024-10-27 09:34:50

代码中的类/结构驱动程序似乎没有定义运算符 ==() ,因此编译器会抱怨。

The class/struct driver in your code doesn't seem to have defined the operator ==() and because of that the compiler is complaining.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文