简体   繁体   中英

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

I'm a C++ beginner, many questions around me. I have defined != operator of int_node , but when I compile this code, show error:

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

The IDE that I use is xcode 4.6.

Below is my all code

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

My compiler says

"1>main.cpp(28): error C2676: binary '!=' : 'int_node' does not define this operator or a conversion to a type acceptable to the predefined operator"

which is true.

We could define != in terms of == eg for your missing int_node

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

You need to define the operators - should they check the node as well?

BTW, do you intend to return first no matter what?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM