[英]invalid operands to binary expression ('int_node' and const 'int_node')
I'm a C++ beginner, many questions around me. 我是C ++初学者,周围有很多问题。 I have defined
!=
operator of int_node
, but when I compile this code, show error: 我已经定义了
int_node
!=
运算符,但是当我编译这段代码时,显示错误:
invalid operands to binary expression ('int_node' and const 'int_node')
二进制表达式的无效操作数(“ int_node”和const“ int_node”)
The IDE that I use is xcode 4.6. 我使用的IDE是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"
“ 1> main.cpp(28):错误C2676:二进制'!=': 'int_node'未定义此运算符或未转换为预定义运算符可接受的类型”
which is true. 没错
We could define !=
in terms of ==
eg for your missing 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);}
You need to define the operators - should they check the node as well? 您需要定义运算符-他们是否也应该检查节点?
BTW, do you intend to return first
no matter what? 顺便说一句,你打算回
first
不管是什么?
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; struct int_node
本身与const int_node &
实例之间未定义任何比较运算符,它可以回答您的问题; 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. 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.