![](/img/trans.png)
[英]invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'const std::vector<int>')
[英]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.