代码之家  ›  专栏  ›  技术社区  ›  Ethan

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

  •  0
  • Ethan  · 技术社区  · 12 年前

    好的,我有一个类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 回复  |  直到 12 年前
        1
  •  2
  •   Luchian Grigore sgryzko    12 年前

    你不能只使用非- static 成员们喜欢这样。我认为下面的例子可以说明问题:

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

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

    我不是说让会员 静止的 ,那是错误的,但要重新考虑你的方法。

    看看如何 std 迭代器是。