2017-09-26 78 views
0

我正在嘗試創建鏈接列表類並定義迭代器,除了最後一個之外,我都擁有它們。我不明白怎麼解決,我得到這個錯誤,當我編譯我的代碼:「!運算符=」!沒有匹配的運算符!=

敵不過在「recList.SortedList ::開始T =記錄= recList.SortedList ::結束T =記錄' a1q1main.cpp:114:37:備註:候選人是: sortedlist.h:112:11:note:SortedList :: iterator SortedList :: iterator :: operator!=(bool)[with T =記錄,排序列表:迭代=排序列表:迭代] sortedlist.h:112:11:注意:從「排序列表:迭代」到「布爾」的參數1沒有已知的轉換

它使上無論我做什麼,都會顯示此錯誤 我已經宣佈的==操作符,一切都很好,但抱怨=這裏 是代碼:

class SortedList { 
struct Node { 
    T data_; 
    Node* next_; 
    Node* prev_; 
    Node(const T& data = T{}, Node* next = nullptr, Node* prev = nullptr) { 
     data_ = data; 
     next_ = next; 
     prev_ = prev; 
    } 
}; 
Node* head_; 
Node* tail_; 
    public: 
class const_iterator { 
protected: 
    Node* curr_; 
public: 
    const_iterator(Node* p) { 
     curr_ = p; 
    } 
......... 
    const_iterator operator--(int) { 
     const_iterator tmp = *this; 
     curr_ = curr_->prev_; 
     return tmp; 
    } 
    const T& operator*() const { 
     return curr_->data_; 
    } 


    const_iterator operator==(bool){ 
      return false; 
    } 

    const_iterator operator!=(bool){ 
      return true; 
    } 

return;` 

我需要滿足以下條件: 運營商= 返回true,如果兩個迭代器指向不同節點,否則爲false O(1)

我沒有完成操作的邏輯,我只是​​需要正確地聲明它,所以我不得到錯誤

+1

'運營商='(在大多數情況下),另需迭代器,並返回一個布爾值,請檢查您的簽名 – YiFei

+1

簽名應該是這樣的['布爾運算符=(L,R);'!(HTTP:// EN。 cppreference.com/w/cpp/language/operator_comparison)。作爲獨立的朋友功能。或者可能是'bool operator!=(OTHER)'作爲成員。你已經將它們定義爲採用bool參數並返回一個迭代器。 –

+0

首先,如果我添加兩個參數到它抱怨的函數,並說我只需要傳遞一個參數,其次是所有的布爾操作符!=()不會改變這種情況,同樣的錯誤彈出 – Oleh

回答

1

您的操作符重載的簽名是不正確的。你讓他們接受一個bool並返回一個迭代器。它應該是相反的。

考慮操作要執行

if(it1 == it2){ 
    // do stuff 
} 

你甚至不顧需要迭代的返回值的簽名返回你的函數的布爾。

而是實現操作符重載中所需的簽名

bool operator==(sorted_list_iterator it){ 
    return (curr_->data_ == it.curr_->data_); 
} 

bool operator!=(sorted_list_iterator it){ 
    return !(*this == it); 
} 

注意您可以使用您operator==超載在operator!=以避免兩個功能重複平等邏輯。您可能還需要在這些功能中允許爲空curr_。 !

+0

謝謝,我明白瞭如果此答案非常有用,請立即修復 – Oleh

+0

隨時註冊並標記爲已接受,以便任何在將來遇到同樣問題的人都可以放心使用此答案。 –