2012-08-23 95 views
0

好吧,我有一个类LinkedList,它带有一个嵌套类LinkedListIterator。在LinkedListIterator的方法中,我引用了LinkedList的私有字段。我认为这是合法的。但我得到的错误:C++ - 从嵌套类使用类'元素?

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

当提出涉及编译或链接器错误的问题时,尽可能完整地发布错误消息的_all_有助于解决问题。即只是将它们逐字地复制粘贴到问题中。 –

+0

请看这里http://stackoverflow.com/questions/486099/can-inner-classes-access-private-variables – jogojapan

+0

@jogojapan完全不同的问题,但答案显示内部类有一个外部类实例的引用,这是解决这个问题的一种方法。 –

回答

2

您不能只使用非static这样的成员。我想下面的例子将清除的事情了:

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

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

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

看看std迭代器是如何。

+0

啊我只是想出我需要做什么......谢谢! – Ethan

+1

那么,如果这个答案是正确的,你应该接受它。 –