C++ -- 使用嵌套类中的类元素?

C++ -- Using a class' elements from a nested class?

本文关键字:元素 嵌套 C++      更新时间:2023-10-16

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

不能像那样只使用非static成员。我认为下面的例子可以说明问题:

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

方法中的currenttail是什么?没有LinkedList的实例,所以这些成员甚至还不存在。

我并不是说让成员成为static,这是错误的,但请重新考虑你的方法。

看看std迭代器是怎样的。