-2

我想对我的代码发表意见。我的自定义容器需要一个随机访问迭代器。如果我阅读了 C++ 2011 标准,特别是第 24 章,我明白实现可能如下:

class my_iterator : public std::iterator<std::random_access_iterator_tag, my_element>
{
    private:
       my_container *_ref;
       my_iterator_state state; // some useful state
    public:
       my_iterator ();
       my_iterator (const my_iterator &);
       my_iterator (my_iterator &&);
       ~my_iterator ();
       my_iterator &operator = (const my_iterator &);
       my_iterator &operator = (my_iterator &&);
       reference operator * ();
       my_iterator &operator ++ ();
       bool operator != (my_iterator);
       value_type operator * ();
       pointer operator -> ();
       my_iterator &operator * ();
       void operator ++ (int);
       value_type operator ++ (int);
       const my_iterator &operator ++ (int);
       reference operator ++ (int);
       my_iterator &operator -- ();
       const my_iterator operator -- (int);
       reference operator -- (int);
       my_iterator &operator += (difference_type);
       my_iterator operator + (difference_type);
       my_iterator operator - (difference_type);
       reference operator [] (difference_type);
       bool operator < (my_iterator);
       bool operator > (my_iterator);
       bool operator <= (my_iterator);
       bool operator >= (my_iterator);
       friend difference_type (my_iterator, my_iterator);
       friend my_iterator operator + (difference_type, my_iterator);
       friend void swap (iterator &, iterator &);
};

void swap (iterator &, iterator &);
difference_type (my_iterator, my_iterator);
my_iterator operator + (difference_type, my_iterator);

上述实现是否正确且功能齐全?成员太多了?

4

1 回答 1

3

通常,您不能使用具有相同参数但返回类型不同的重载,因此您的几个成员不能存在。您应该保留以下内容:

reference operator * ();
my_iterator operator ++ (int);
my_iterator operator -- (int);

并删除虚假的重载:

value_type operator * ();
void operator ++ (int);
value_type operator ++ (int);
const my_iterator &operator ++ (int);
reference operator ++ (int);
const my_iterator operator -- (int);
reference operator -- (int);

这没有任何意义:

friend difference_type (my_iterator, my_iterator);

我认为应该是:

friend difference_type operator-(my_iterator, my_iterator);

而你似乎不见了operator-=

于 2013-05-10T15:29:17.330 回答