二进制表达式的操作数无效("int_node"和常量"int_node")

invalid operands to binary expression ('int_node' and const 'int_node')

本文关键字:int node 常量 二进制 操作数 无效 表达式      更新时间:2023-10-16

我是C++初学者,周围有很多问题。我定义了int_node!=运算符,但当我编译此代码时,显示错误:

二进制表达式('int_node'和const'int_node')的操作数无效

我使用的IDE是xcode 4.6。

下面是我的全代码

typedef struct int_node{
    int val;
    struct int_node *next;
} int_t;
template <typename Node>
struct node_wrap{
    Node *ptr;
    node_wrap(Node *p = 0) : ptr(p){}
    Node &operator *() const {return *ptr;}
    Node *operator->() const {return ptr;}
    node_wrap &operator++() {ptr = ptr->next; return *this;}
    node_wrap operator++(int) {node_wrap tmp = *this; ++*this; return tmp;}
    bool operator == (const node_wrap &i) const {return ptr == i.ptr;}
    bool operator != (const node_wrap &i) const {return ptr != i.ptr;}
} ;
template <typename Iterator, typename T>
Iterator find(Iterator first, Iterator last,  const T& value)
{
    while (first != last && *first != value) // invalid operands to binary experssion ('int_node' and const 'int_node')
    {
        ++first;
        return first;
    }
}
int main(int argc, const char * argv[])
{
    struct int_node *list_head = nullptr;
    struct int_node *list_foot = nullptr;
    struct int_node valf;
    valf.val = 0;
    valf.next = nullptr;
    find(node_wrap<int_node>(list_head), node_wrap<int_node>(list_foot), valf);
    return (0);
}

我的编译器说

"1>main.cpp(28):错误C2676:binary"!=":"t_node"未定义此运算符或到类型的转换预定义操作员可接受"

这是真的。

我们可以根据==定义!=,例如您丢失的int_node

bool operator == (const int_node &i) const {return val == i.val;}
bool operator != (const int_node &i) const {return !(*this==i);}

您需要定义运算符-他们是否也应该检查节点?

顺便说一句,你打算无论如何都归还first吗?

while (first != last && *first != value)
{
    ++first;
    return first;
    //     ^^^^^
    //     |||||
}

我看到了两件事:

  • struct int_node在它自己和const int_node &实例之间没有定义任何比较运算符,它回答了您的问题
  • 在函数Iterator find(Iterator first, Iterator last, const T& value)中,while语句中有一个return语句,因此while是无用的,或者return应该放在它之外