【问题标题】:Linked list const iterator链表常量迭代器
【发布时间】:2014-03-20 09:35:36
【问题描述】:

我已经实现了一个双向链表,并创建了一个扩展 std::iterator 的迭代器。我现在正在尝试创建一个const 版本。

我试过了:

typename typedef list_iterator<T_>        iterator;
typename typedef list_iterator<T_> const  const_iterator;

如果我这样做,我会得到这个错误:

error C2678: binary '--' : no operator found which takes a left-hand operand of type 'const    list_iterator<T_>' (or there is no acceptable conversion)

这是我的operator--

list_iterator& operator -- ()
{
    _current = _current->_previous;
    return *this;
}

list_iterator operator--(int) // postfix
{
    list_iterator hold = *this;
    --*this;
    return list_iterator( hold );
}

如果我放了

list_iterator operator--() const

...我无法修改_current的值

如何使我的迭代器现在像const_iterator 一样工作,以便从我的链接列表中我可以调用获取begin()end() 的const 版本,以及cbegin()cend()

【问题讨论】:

  • 尝试声明 _current 可变
  • const_iteratorconst iterator非常不同的东西。他们实际上需要是两种不同的类型,抱歉。这是“指向数据的常量指针”和“指向常量数据的指针”之间的区别
  • 那么我需要创建一个全新的迭代器类吗?

标签: c++ linked-list operator-overloading const-iterator


【解决方案1】:

没错。问题是你声明你的 const_iterator typedef。 (见How to correctly implement custom iterators and const_iterators?

代替

typename typedef list_iterator<T_> const  const_iterator;

你想要的

typename typedef list_iterator<const  T_> const_iterator;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2016-03-02
    • 2016-01-09
    • 2018-10-06
    • 2016-07-08
    相关资源
    最近更新 更多