C++ iterator and const_iterator problem for own container class

后端 未结 3 2099
猫巷女王i
猫巷女王i 2020-12-09 05:10

I\'m writing an own container class and have run into a problem I can\'t get my head around. Here\'s the bare-bone sample that shows the problem.

It consists of a con

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-09 05:42

    When you call begin() the compiler by default creates a call to the non-const begin(). Since myc isn't const, it has no way of knowing you mean to use the const begin() rather than the non-const begin().

    The STL iterator contains a cast operator which allows an iterator to be silently converted to a const_iterator. If you want this to work you need to add one as well like so:

    class iterator
    {
    public:
        typedef iterator self_type;
        inline iterator() { }
    
        operator const_iterator() { return const_iterator(); }
    };
    

    or allow const_iterator to be constructed from an iterator like so:

    class const_iterator
    {
    public:
        typedef const_iterator self_type;
    
        const_iterator(iterator& ) {}
        inline const_iterator() { }
    };
    

提交回复
热议问题