2013-02-06 2 views
2

, создавая некоторые старые структуры данных в C++. В настоящее время я имею вопрос с двусвязным списком классом:C++ не называет тип

list.h:

template <class T> 
class List{ 

private: 

int size; 

struct listNode{       
    T data; 
    listNode* next; 
    listNode* prev; 
    listNode(T newData); 
}; 

listNode * head;      
listNode * tail;      
listNode * curr;      
listNode * find(listNode * place, int k); 
void removeCurrent(listNode * temp);  
public: 

List(); 
int getSize() const;     
void insert(int loc, T data);  
void remove(int loc);   
T const & getItem(int loc) const; 
void print(); 

};

List.cpp:

#include "List.h" 
#include <iostream> 

using namespace std; 

template<class T> 
List<T>::List(){ 
size = 0; 
head->next = tail; 
head->prev = NULL; 
tail->prev = head; 
tail->next = NULL; 


} 

// getSize: public method that returns the size of the list 
template<class T> 
int List<T>::getSize() const { 
    return size; 
} 

// insert: public method that inserts data into the list 
template<class T> 
void List<T>::insert(int loc, T data){ 
    if(loc <1){ 
     cout<<"Invalid Location"<<endl; 
     return; 
    } 
    curr = find(head,loc-1); 
    listNode * newNode = new listNode(data); 
    newNode->next = curr->next; 
    newNode->prev = curr; 
    newNode->next->prev = newNode; 
    curr->next = newNode; 
    size++; 
} 

// remove: public method that inserts data into the list 
template<class T> 
void List<T>::remove(int loc){ 
    if(loc <1){ 
     cout<<"Invalid Location"<<endl; 
     return; 
    } 
    curr = find(head,loc); // Find the node infront of the target 
    removeCurrent(curr); // Remove that node 
} 

// removeCurrent: helper function that removes the current node 
template<class T> 
void List<T>::removeCurrent(listNode* temp){ 
    listNode* t = temp->next; 
    temp->data = t->data;  // HACK: take data from next node 
    temp->next = t->next; 
    t->next->prev = temp; 
    delete t; 
    t=NULL; 
    size--; 
} 

// find: private helper function that returns a pointer to the k-1 node 
template<class T> 
listNode * List<T>::find(listNode * place, int k){ 
    if((k==0) || (place==NULL)) 
     return place; 
    else return find(place->next,k-1); 
} 

// getItem: returns data at location loc 
template<class T> 
T const& List<T>::getItem(int loc) const{ 
    curr = find(head,loc); 
    return curr->data; 
} 

// print: prints the sequence of variables in the list 
template<class T> 
void List<T>::print() 
{ 
    curr = head; 
    while(curr->next != tail){ 
     curr = curr->next; 
     cout<<curr->data<<endl; 
    } 
} 

//listNode constructor 
template<class T> 
List<T>::listNode::listNode(T newdata):data(newdata),next(NULL),prev(NULL) 
{} 

Ошибка я получаю следующие:

error: 'listNode' does not name a type.

Я попробовал различные предложения, предлагаемые в подобных сообщений по устранению неполадок, но я все еще получаю это ошибка. У меня есть main.cpp, который включает List.cpp, но он практически пуст.

+2

Поскольку вы определили struct listNode в списке классов, его тип - List :: listNode. –

+0

На линии ведьмы есть ошибка? – Fox32

+0

cli_hlt ударил ноготь по голове - вы объявили listNode внутри класса, поэтому его нужно префикс с именем класса. –

ответ

3

Вы будете иметь, чтобы определить, какие listNode вы говорите в обратном типе find метода, так как вы определили его в качестве члена List класса, и вы также будете иметь, чтобы использовать typename (потому что List<T> является зависимым объемом).

template <class T> 
typename List<T>::listNode* List<T>::find(listNode* place, int k) 
{ 
    if ((k == 0) || (place == NULL)) 
     return place; 
    else 
     return find(place->next, k-1); 
} 

Предполагая, что вы используете C++ 11, вы также можете использовать nullptr вместо NULL, поскольку его более безопасным и использовать список инициализации в List конструктора.

+0

Не использовать C++ 11 еще - я немного отставал от времени, но это сработало! Спасибо! – Erroldactyl