错误:'struct List'需要模板参数

Hol*_*lly 3 c++ templates compiler-errors

我正在尝试为List类创建自己的模板作为学习练习.我在模板语法方面遇到了一些问题,现在我收到以下错误消息..

main.cpp|Line 8|instantiated from here
error: template argument required for 'struct List'
In function 'int main()':
...
Run Code Online (Sandbox Code Playgroud)

据我所知,我不会滥用任何东西,但这是我第一次使用模板,并且非常感谢有人翻阅并让我知道我做错了什么.

List.hpp:

#if !defined _LIST_HPP_
#define _LIST_HPP_

#include "Node.hpp"

///since we're creating a template everything must be defined in the hpp

template <typename ListType>
class List
{
   public:
      List();
      bool Empty();
      void PushFront();
      void PushBack();
      void PopBack();
      Node<ListType>& GetHead();

   private:
      int _size;
      Node<ListType>* _head;
      Node<ListType>* _tail;
};


///implement List class here
template <typename ListType>
List<ListType>::List() : _head(0), _tail(0), _size(0)
{
}
template <typename ListType>
bool List<ListType>::Empty()
{
   return _size == 0;
}
template <typename ListType>
void List<ListType>::PushFront()
{
   _head = new Node<ListType>( _head , 0 );
   if (!Empty())
      _head->_prev->_next = _head; //set previous nodes _next to new _head

   ++_size;
}
template <typename ListType>
void List<ListType>::PushBack()
{
   _tail = new Node<ListType>( 0 , _tail);
   if (!Empty())
      _tail->_next->_prev = _tail; // set old tails _prev to new tail

   ++_size;
}
template <typename ListType>
void List<ListType>::PopBack()
{

}
template <typename ListType>
Node<ListType>& List<ListType>::GetHead()
{
   return _head;
}

#endif //define
Run Code Online (Sandbox Code Playgroud)

Node.hpp:

#if !defined _NODE_HPP_
#define _NODE_HPP_


template<typename NodeType>
class Node{
   public:
      Node( Node* prev = 0, Node* next = 0);
      void SetData(NodeType newData);
      void GetData();
   private:
      friend class List;

      NodeType _data;
      Node* _next;
      Node* _prev;

};


///implement Node

template <typename NodeType>
Node<NodeType>::Node(Node* prev, Node* next) : _prev(prev), _next(next)
{}
template <typename NodeType>
void Node<NodeType>::SetData(NodeType newData)
{
   _data = newData;
}
template <typename NodeType>
void Node<NodeType>::GetData()
{
   return _data;
}

#endif //define
Run Code Online (Sandbox Code Playgroud)

Main.hpp

#include <iostream>
#include "List.hpp"
int main()
{
   List<int> testl;
      //test
      testl.PushFront();
      testl.GetHead().SetData(7); //Error thrown here??
      std::cout << test1.GetHead().GetData() << std::endl;

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*itb 6

List 是一个类模板,所以你需要在你的朋友声明中声明它

template<typename ListType>
friend class List;
Run Code Online (Sandbox Code Playgroud)

如果你只想List<NodeType>成为一个朋友,你需要告诉它模板参数,那么朋友声明就变成了

friend class List<NodeType>;
Run Code Online (Sandbox Code Playgroud)

为了使其工作,它需要知道List作为类模板存在,所以你需要在它的顶部向前声明它Node.hpp:

template<typename ListType>
class List;
Run Code Online (Sandbox Code Playgroud)