Call a non-const member function from a const member function

后端 未结 7 1716
情深已故
情深已故 2020-12-29 06:15

I would like to know if its possible to call a non-const member function from a const member function. In the example below First gives a compiler error. I understand why it

7条回答
  •  醉酒成梦
    2020-12-29 06:58

    iterators are similar in this and make an interesting study.

    const iterators are often the base for 'non const' iterators, and you will often find const_cast<>() or C style casts used to discard const from the base class with accessors in the child.

    Edit: Comment was

    I have a zip iterator where the const one inherits from the non-const

    This would generally be the wrong inheritence structure (if your saying what I think you are), the reason being that children should not be less restrictive than parents.

    say you had some algorithm taking your zip iterator, would it be appropriate to pass a const iterator to a non const ?

    if you had a const container, could only ask it for a const iterator, but then the const iterator is derived from an iterator so you just use the features on the parent to have non const access.

    Here is a quick outline of suggested inheritence following the traditional stl model

    class ConstIterator: 
        public std::_Bidit< myType, int, const myType *, const mType & >
    {
      reference operator*() const { return m_p; }
    }
    
    class Iterator : public ConstIterator 
    {
      typedef ConstIterator _Mybase;
      // overide the types provided by ConstIterator
      typedef myType * pointer;
      typedef myType & reference;
    
      reference operator*() const
      { 
        return ((reference)**(_Mybase *)this);
      }
    }
    
    typedef std::reverse_iterator ConstReverseIterator;
    typedef std::reverse_iterator ReverseIterator;
    

提交回复
热议问题