2012-02-25 57 views
0

此代码不在我的系统中编译;我正在使用Eclipse。链接列表未编译

// Linked list head 
template<class T> 
struct Node 
{ 
    // constructor 
    Node(const T& a) : pNext(NULL), data(a) {} 
    Node* pNext; //link 
    T data; 
}; // end of header 


// List code 
#include <iostream> 
#include "LinkedList.h" 

template<class T> 
class linkedList 
{ 
public: 
    typedef Node<T> Node; 
    //constructor creates empty list 
    linkedList() : pHead(NULL), size(0) {} 

~linkedList() 
{ 
    Node* pIter = pHead; 
    while(pIter != NULL) 
    { 
     Node* pNext = pIter->pNext; 
     delete pIter; 
     pIter = pNext; 
    } 
} 

void insert(const T& data) 
{ 
    Node* pInsert = new Node(data); 
    if(pHead == NULL) 
    { 
     pHead = pInsert; 
    } 
    else 
    { 
     pInsert->pNext = pHead; 
     pHead = pInsert; 
    } 
} 

private: 
    Node* pHead; // always points to head of list 
    unsigned int size; // stores number of elements in list 
}; 

以下是错误消息:

./LinkedList.cpp:14:18: error: declaration of 'typedef struct Node<T> linkedList<T>::Node' 
../LinkedList.h:4:1: error: changes meaning of 'Node' from 'struct Node<T>' 
make: *** [LinkedList.o] Error 1 

回答

4

的错误是相当清楚的:不要再使用该名称Node。相反,你可以写这样的事情:

typedef Node<T> node_type; 

模板名称和类型名称使用C共享同一命名空间++,所以你不能为两个不同的实体使用相同的名称,即使一个是一个模板,另一种类型。

(有点相切,存在周围标签名称无论是在C和C++微妙的相当数量; this article可能是值得的读取,和this和​​)