Basic template linked list

会有一股神秘感。 提交于 2021-02-10 07:40:09

问题


#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 ;
}

I am trying to write a template version of linked list. I ran into some errors and unsure why. The error occurs when I try to make friend class LinkedList, I need to do this so I can access T data from LinkedList.

: 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

回答1:


You're missing a semicolon at the end of your class definition for LinkedList. However, even if you fix that, since Node<T> needs to know about LinkedList<T> and vice versa, you'll need to declare them up the top:

#include <iostream>
#include <string>

using namespace std;

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

//Code as before


来源:https://stackoverflow.com/questions/13577324/basic-template-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!