2012-11-27 49 views
2
#include <iostream> 
#include <string> 

using namespace std; 

template <class T> 
class Node{ 
     friend class LinkedList<T>; 
private: 
    T data; 
    Node <T> *next; 
public: 
    Node(); 
    Node(T d); 
    ~Node(); 
}; 

template <class T> 
Node<T>::Node(){ 
    T data = 0; 
    next = 0; 
} 

template <class T> 
Node<T>::Node(T d){ 
    data = d; 
    next = 0; 

} 

template<class T> 
Node<T>::~Node(){ 
    delete next; 
} 

template <class T> 
class LinkedList{ 
private: 
    Node <T> *head; 
public: 
    LinkedList(); 
    ~LinkedList(); 
    void Push_Front(const T& e); 
} 

template<class T> 
LinkedList <T>::LinkedList(){ 
    head = 0; 
} 

template <class T> 
LinkedList<T>::~LinkedList(){ 
    delete head; 
} 

template <class T> 
void LinkedList<T>::Push_Front(const T &e){ 
    Node<T> *newNode = new Node<T>(e); 

    if(head == 0) 
     head = new Node<T>(e); 

    newNode->next = head; 
    head = newNode; 
} 


void main(){ 
    LinkedList<int> list; 

    list.Push_Front(10); 


    int t; 
    cin>>t; 
    return ; 
} 

我想寫一個鏈接列表的模板版本。我遇到了一些錯誤,並不確定原因。當我嘗試使朋友類LinkedList發生錯誤時,我需要這樣做,以便我可以從LinkedList訪問T數據。基本模板鏈表

: error C2059: syntax error : '<' 
: see reference to class template instantiation 'Node<T>' being compiled 
: error C2238: unexpected token(s) preceding ';' 
: error C2143: syntax error : missing ';' before 'template' 
: error C2989: 'LinkedList' : class template has already been declared as a non-class template 
: see declaration of 'LinkedList' 
: 'LinkedList': multiple template parameter lists are not allowed 
: error C2988: unrecognizable template declaration/definition 
: error C2059: syntax error : '<' 
: error C2588: '::~LinkedList' : illegal global destructor 
: fatal error C1903: unable to recover from previous error(s); stopping compilatio 
+0

請後確切的錯誤信息。 –

+0

考慮在LinkedList中嵌套節點,你不需要朋友 – Lou

+1

缺少分號。 – Pubby

回答

1

您在LinkedList的類定義末尾丟失了分號。但是,即使你解決這個問題,因爲Node<T>需要了解LinkedList<T>,反之亦然,你需要他們宣告了頂部:

#include <iostream> 
#include <string> 

using namespace std; 

template <typename T> class Node; 
template <typename T> class LinkedList; 

//Code as before 
+0

感謝模板 class Node; template class LinkedList;訣竅 – Instinct