繁体   English   中英

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

[英]invalid operands to binary expression ('int_node' and const 'int_node')

我是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:二进制'!=': '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;
    //     ^^^^^
    //     |||||
}

我在那里看到两件事:

  • struct int_node本身与const int_node &实例之间未定义任何比较运算符,它可以回答您的问题;
  • Iterator find(Iterator first, Iterator last, const T& value)函数Iterator find(Iterator first, Iterator last, const T& value)中, while语句内有一个return语句,因此while没用,否则应将return值放在它的外面。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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