2012-11-27 3 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 안에 Node를 중첩하는 것을 고려하면 친구가 필요하지 않습니다. – 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

감사 템플릿 클래스 Node; 템플릿 클래스 LinkedList; 트릭을 했어. – Instinct