c++ abstract class with nested class. derived class and nested class

∥☆過路亽.° 提交于 2019-12-05 01:57:45

Taking into account your design constraints that you cannot use templates, than one thing should change: add interface IteratorImpl. Thus you can make class Iterator from base class Container non virtual. It needs to be non-virtual since STL-alike iterators should have value semantics. See pimpl idiom for more details how it works!

Like this:

typedef int value_type;
class Container 
{
    protected:
        class IteratorImpl
        {   
        public:
            virtual void next() = 0;
            virtual IteratorImpl* clone() const = 0;
            virtual value_type get() const = 0;
            virtual bool isEqual(const IteratorImpl& other) const = 0;
        };

    public:
        class Iterator 
        {   
        public:
            Iterator(IteratorImpl* impl) : impl(impl) {}
            ~Iterator() { delete impl; }
            Iterator(const Iterator& other) : impl(other.impl->clone()) {}
            Iterator& operator=(const Iterator& other) {
              IteratorImpl* oldImpl = impl;
              impl = other.impl->clone();
              delete oldImpl;
            }
            bool operator == (const Iterator& other) const 
            {
               return impl->isEqual(*other->impl);
            }
            Iterator& operator ++ ()
            {
                impl->next();
                return *this;
            }
            value_type& operator*() const 
            {
               return impl->get();
            }
            value_type* operator->() const
            {
               return &impl->get();
            }
        };
        Container();
        Container(const Container& other);
        ~Container();   

    virtual value_type& front() const=0;
    virtual value_type& back() const=0;
    virtual Iterator begin() const=0; // 
    ...
    };

Then in your derived just implement IteratorImpl:

class Linked_list:public Container 
{
protected:
    class IteratorImpl: public Container::IteratorImpl
    {
       ....
    };

public:
    Iterator begin() const { return new IteratorImpl(firstNode); }
    Iterator end() const { return new IteratorImpl(nodeAfterLastNode); }

...
};

These firstNode and nodeAfterLastNode are just my guess - use whatever you need to implement the IteratorImpl interface...

You should define a const_value_type to represent const value_type, and use it for the return values of the front and back virtual methods. Alternatively you can drop the const qualifiers on these methods, because having non const reference return types on const methods doesn't make sense.

Without more details on the classes, it's difficult to tell for the rest. You could also have a look at early implementations of the STL: it's a very good way to get some insight on these topics.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!