【问题标题】:no match for operator!=运算符不匹配!=
【发布时间】:2017-09-26 02:19:45
【问题描述】:

我正在尝试创建链表类并定义迭代器,除了最后一个之外,我拥有所有迭代器。我不知道如何修复,当我编译我的代码时出现此错误:

“recList.SortedList::begin with T = Record != recList.SortedList::end with T = Record”中的“operator!=”不匹配 a1q1main.cpp:114:37:注意:候选人是: sortedlist.h:112:11: 注意:SortedList::iterator SortedList::iterator::operator!=(bool) [with T = Record, SortedList::iterator = SortedList::iterator] sortedlist.h:112:11:注意:没有已知的参数 1 从‘SortedList::iterator’到‘bool’的转换

无论我做什么,它都会一直显示此错误 我已经声明了 operator == 并且一切都很好,但是 != 抱怨 这是代码:

 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)

我没有完成算子的逻辑,我只需要正确声明它,所以我不会收到错误

【问题讨论】:

  • operator!=(在大多数情况下)采用另一个迭代器并返回一个布尔值,检查您的签名
  • 签名应该像bool operator!=(L, R);。作为一个独立的朋友功能。或者可能bool operator!=(OTHER) 作为成员。您已将它们定义为采用 bool 参数并返回迭代器。
  • 首先,如果我向它抱怨的函数添加两个参数并说我只需要传递一个参数,第二个布尔运算符!=() 不会改变这种情况并且会弹出相同的错误向上

标签: c++ list iterator


【解决方案1】:

您的运算符重载的签名不正确。你让他们接受一个布尔值并返回一个迭代器。应该是相反的。

考虑您正在执行的操作

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_

【讨论】:

  • 很酷,如果这个答案有用,请随时点赞并标记为已接受,以便将来遇到相同问题的任何人都可以放心使用此答案。
猜你喜欢
  • 2012-03-12
  • 2013-09-29
  • 1970-01-01
  • 1970-01-01
  • 2014-12-09
  • 2018-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多