我是一个 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);
}
Run Code Online (Sandbox Code Playgroud)
我的编译器说
“1>main.cpp(28): error C2676: binary '!=' : '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);}
Run Code Online (Sandbox Code Playgroud)
您需要定义运算符 - 他们是否也应该检查节点?
BTW,无论如何你都打算回去first吗?
while (first != last && *first != value)
{
++first;
return first;
// ^^^^^
// |||||
}
Run Code Online (Sandbox Code Playgroud)