2015-09-06 343 views
1

嘗試創建使用LinkedListNode類的鏈接列表時遇到了一些問題。在List類中,如何創建headcurrtemp對象?我認爲我可以將它們初始化爲對象,然後它會調用默認的Node()構造函數,併爲它們分配一個數據和指針變量。但我得到的錯誤:‘Node’ does not name a type‘head’ was not declared in this scope對象head,currtemp。 這裏是我的代碼:錯誤:未命名類型(C++)

LinkedList.cpp:

#include <iostream> 
#include <cstdlib> 
#include "LinkedList.h" 
#include "Node.h" 

using namespace std; 

LinkedList::LinkedList() { 
    head = NULL; 
    curr = NULL; 
    temp = NULL; 

    cout << "Blank list created." << endl; 
} 

LinkedList::LinkedList(value_type addData) { 
    Node n(addData); 
} 

LinkedList.h:

class LinkedList { 
    public: 
     typedef std::string value_type; 

     LinkedList(); 
     LinkedList(value_type addData); 

    private:   
     Node head; 
     Node curr; 
     Node temp; 
}; 

Node.cpp:

#include <iostream> 
#include <cstdlib> 
#include "Node.h" 

using namespace std; 

Node::Node() { 
    nodePtr n = new node; 
    n->next = NULL; 
    n->data = NULL; 

} 

Node::Node(value_type addData) { 
    nodePtr n = new node; 
    n->next = NULL; 
    n->data = addData; 

} 

Node.h:

class Node { 
    public: 
     typedef std::string value_type; 

     Node(); 
     Node(value_type addData); 
    private: 
     struct node { 
      value_type data; 
      node* next; 
     }; 

     typedef struct node* nodePtr; 

}; 

任何幫助將不勝感激,謝謝你們!

+0

將'#include「Node.h」'添加到'LinkedList.h'。 – songyuanyao

回答

0

看看編譯器用LinkedList.c做什麼。它始於此:

... 
#include "LinkedList.h" 
#include "Node.h" 
... 

然後評估#include指令,和拉動LinkedList.hNode.h到源:

... 
class LinkedList { 
... 
    Node head; 
    Node curr; 
    Node temp; 
}; 

class Node { 
... 
}; 

,然後嘗試編譯此,獲取儘可能「節點頭; 「 (當它尚未達到類Node的聲明時),並抱怨它不知道你在說什麼。

聲明class LinkedList的文件需要知道什麼是Node。將#include "Node.h"放在LinkedList.h的頂端附近(並將標頭警衛添加到Node.h),您不會遇到此問題。

+0

啊,好的。那麼我試過了,只是收到了一堆更多的錯誤:[鏈接](http://i.imgur.com/mlRDT1g.png),我不知道他們指的是什麼。我有頭衛兵,只是試圖凝聚這個職位,所以我沒有包括他們。 – Lachie

+2

@Lachie:你編寫了很多代碼而沒有測試任何代碼,然後你解決了停止編譯器在文件頂部的問題;現在編譯器可以超過這一點,並尖叫許多其他錯誤。我認爲從這裏開始的最好方法是簡化代碼,直到沒有錯誤,或者從頭開始,然後慢慢地重新引入複雜性,在每一步都進行測試,並且不會添加無效的代碼。 **(PS你不知道這些錯誤信息是指什麼?Google可以提供幫助,Stack Overflow也是如此。) – Beta

+0

好的,謝謝。 – Lachie