0

好的,所以我有一个类 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;
            }
4

1 回答 1

2

你不能static像那样使用非成员。我认为以下示例将清除问题:

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

current方法内部会tail是什么?没有实例LinkedList可言,所以这些成员甚至还不存在。

我不是说让成员static,那是错误的,但请重新考虑您的方法。

看看std迭代器是怎样的。

于 2012-08-23T06:13:12.100 回答