C++ - Использование элементов класса из вложенного класса?

Итак, у меня есть класс LinkedList с вложенным классом LinkedListIterator. В методах LinkedListIterator я ссылаюсь на частные поля LinkedList. Который я считал законным. Но я получаю ошибку:

from this location

каждый раз, когда я ссылаюсь на них.

И я получаю соответствующие сообщения об ошибках на полях в вмещающем классе:

invalid use of non-static data member 'LinkedList<int>::tail'

Есть идеи почему? Соответствующий код ниже:

template<class T>
class LinkedList {

    private:
        //Data Fields-----------------//
        /*
         * The head of the list, sentinel node, empty.
         */
        Node<T>* head;
        /*
         * The tail end of the list, sentinel node, empty.
         */
        Node<T>* tail;
        /*
         * Number of elements in the LinkedList.
         */
        int size;

    class LinkedListIterator: public Iterator<T> {

            bool add(T element) {

                //If the iterator is not pointing at the tail node.
                if(current != tail) {

                    Node<T>* newNode = new Node<T>(element);
                    current->join(newNode->join(current->split()));

                    //Move current to the newly inserted node so that
                        //on the next call to next() the node after the
                        //newly inserted one becomes the current target of
                        //the iterator.
                    current = current->next;

                    size++;

                    return true;
                }

                return false;
            }

1 ответ

Решение

Вы не можете просто использовать неstatic участники как это. Я думаю, что следующий пример прояснит ситуацию:

LinkedList<int>::LinkedListIterator it;
it.add(1);

Что бы current а также tail быть внутри метода? Там нет ни одного случая LinkedList говорить о, так что эти члены еще даже не существуют.

Я не говорю, чтобы сделать членов staticЭто было бы неправильно, но переосмыслите ваш подход.

Посмотри как std итераторы есть.

Другие вопросы по тегам