2

我是 C++ 初学者,我周围有很多问题。我已经定义!=了运算符 of 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);
}
4

2 回答 2

5

我的编译器说

“1>main.cpp(28): 错误 C2676: 二进制 '!=' : 'int_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;
    //     ^^^^^
    //     |||||
}
于 2013-07-18T16:02:36.107 回答
1

I see two things in there:

  • struct int_node does not define any comparison operator between itself and a const int_node & instance, and that responds to your question;
  • in the function Iterator find(Iterator first, Iterator last, const T& value) there is a return statement within the while statement, so the while is useless, or the return should be put outside it.
于 2013-07-18T16:44:13.430 回答