Generic Linked List error: LinkedList is not a class template

Generic Linked List error: LinkedList is not a class template

// 这是 Node.h 文件

#ifndef NODE
#define NODE                                                                            

template <typename T>
class Node
{
   private:
   T elem;
   Node *next;
   friend class LinkedList<T>;
};

#endif // NODE

这是 LinkedLilst.h 文件

#ifndef LINKED_LIST
#define LINKED_LIST

#include "Node.h"

template <typename T>
class LinkedList
{
public:
  LinkedList();
  ~LinkedList();
  bool empty() const;
  const T &front() const;
  void addFront(const T &e);
  void removeFront();

private:
  Node<T> *head;
};

#endif // LINKED_LIST

这是 LinkedList.cpp 文件

#include <iostream>
#include "LinkedList.h"
using namespace std;

template <typename T>
LinkedList<T>::LinkedList() : head(NULL) {}

template <typename T>
bool LinkedList<T>::empty() const // I don't want it to modify the data member of the function.
{
  return head == NULL;
}

template <typename T>
LinkedList<T>::~LinkedList()
{
  while (!empty())
    removeFront(); 
}
...
...
...


这是我的 main.cpp 文件

#include <iostream>
#include "LinkedList.h"
using namespace std;
int main()
{
  LinkedList<int> ls;
  ls.addFront(3);
  cout << ls.front();
  return 0;
}

我不知道为什么会收到错误消息: 'LinkedList' 不是 class 模板

   friend class LinkedList<T>; in Node.h

问题是 Node.h 文件没有任何与 LinkedList 相关的内容。 我添加了 LinkedList 声明,但它仍然显示错误。 请帮忙。

您需要转发声明 LinkedList class 模板:

#ifndef NODE
#define NODE                                                                            

template<class> class LinkedList;   // <- forward declaration

template <typename T>
class Node
{
   private:
   T elem;
   Node *next;
   friend class LinkedList<T>;
};

#endif // NODE

您要 运行 解决的下一个问题可能是链接问题。我建议将 class 成员函数定义移动到头文件中。 更多相关信息:Why can templates only be implemented in the header file?