2015-12-18 59 views
1

這是一個鏈接列表演示,我定義了一個Node結構,它的指針作爲頭部,但編譯器說:in - valid use of non-在地方靜態成員:嵌套結構:定義結構指針時非法使用非靜態成員

Node* head; 

更進一步,如果我不事先聲明struct Node它會報告未申報的節點。

的代碼如下:

#ifndef LINKLIST_H 
#define LINKLIST_H 

template<typename T> 
class LinkList 
{ 
    struct Node;  //why declaration is required here ??? 

    public: 
    // member function 
     Node* Find(T x); 
    //..... 

    private: 
     struct Node 
     { 
      T data; 
      Node* next; 

     // Node():next(NULL){} 
      Node(const T& d=0, Node* n=NULL):data(d),next(n){} 
     }; 

     Node* head;    //ERROR ?????? why? 
}; 

template<typename T> 
typename LinkList<T>::Node* LinkList<T>::Find(T x) 
{ 
    Node* ptr=head->next; 
    //..... 

}

ENDIF // LINKLIST_H

運行時錯誤:

||=== Build: Release in Broken Keyboard (compiler: GNU GCC Compiler) ===| 
include\LinkList.h|41|error: invalid use of non-static data member 'LinkList<T>::head'| 
include\LinkList.h|22|error: from this location| 
include\LinkList.h|41|error: invalid use of non-static data member 'LinkList<T>::head'| 
include\LinkList.h|95|error: from this location| 
include\LinkList.h|95|error: default argument given for parameter 1 of 'void LinkList<T>::Insert(T, LinkList<T>::Node*)' [-fpermissive]| 
include\LinkList.h|22|error: after previous specification in 'void LinkList<T>::Insert(T, LinkList<T>::Node*)' [-fpermissive]| 
include\LinkList.h|95|error: default argument given for parameter 2 of 'void LinkList<T>::Insert(T, LinkList<T>::Node*)'| 
include\LinkList.h|22|error: after previous specification in 'void LinkList<T>::Insert(T, LinkList<T>::Node*)'| 
||=== Build failed: 8 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===| 
+0

請提供完整的錯誤信息。 –

+0

我加了,請看看。謝謝。 – Qinchen

回答

0

需要結構節點的第一前向聲明因爲您在提供節點定義之前正在使用Find方法。 但是你不應該在Node *頭部出現錯誤。我已經在Visual Studio 2015中試過了你的代碼,並在main中實例化模板,沒有錯誤。

什麼是您的編譯器版本?

阿隆。

+0

我使用代碼塊和模板類聲明和實施在單獨的.h文件。當我在main.cpp中嘗試它時,它運行正常。這麼奇怪!謝謝您的回覆! – Qinchen