Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

c++ - Inner Class access to Outer Class members

I'm very confused about this topic, basically I've this code:

template <typename T>
class SListArray
{
public:
    class const_iterator
    {
    public:
        const_iterator(size_t i_currentNode = -1)
            :m_position(i_currentNode)
        {
        }

        T const& operator*() const
        {
            return m_data[m_position].element;
        }

        // ...

    protected:
        size_t m_position;
    };

    explicit SListArray();

    // ...

private:
    std::vector<Node<T>> m_data;

    // ...
};

This code give me a compiler error, so, I would to know if is possible to give the Inner Class the acces to the members of the Outer Class.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Nested classes already have access to the containing class's members, assuming they have a pointer/reference to the containing class upon which to operate. Your iterator will need to store a reference to the outer class in order to be able to access the container as you appear to want.

Also note that protected data is usually a code smell and should typically be avoided. Prefer private data and a protected interface if appropriate.

EDIT: Unless this is strictly an exercise to learn how to program a container, just use one of the C++ standard containers such as vector which are well developed, debugged, and optimized.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...