2012-08-23 144 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

那麼,如果這個答案是正確的,你應該接受它。 –