Class 模板中嵌套的结构构造函数问题

Issue with Constructor of Struct nested in Class Template

我需要将我写入的整数的链表 class 转换为 class 模板。我遇到了嵌套在列表 Class 中的结构的构造函数和析构函数的问题,称为节点。

布局:

  template <typename T>
  class List
  {
    public:
      //Stuff that's not important to this question
    private:
      struct Node
      {
        Node(T value);              // constructor
        ~Node();                // destructor
        Node *next;             // pointer to the next Node
        T data;               // the actual data in the node
        static int nodes_alive; // count of nodes still allocated
      };
  };

实施:

template <typename T>
typename List<T>::Node::Node(T value)
{
  data = value;
  next = 0;
}

template <typename T>
typename List<T>::Node::~Node()
{
   --nodes_alive;
}

错误:

  1. 应为“;”在声明结束时

    类型名List::Node::Node(T值)

  2. “::”后需要标识符或模板 ID

    typename List::Node::~Node()

  3. 期望在'~'之后的class名称命名一个析构函数

    typename List::Node::~Node()

不太确定这里发生了什么。我的实现位于头文件底部的单独文件中。任何帮助将不胜感激。

很简单:删除 typename 关键字。由于您正在编写 constructor/destructor 并且没有 return 类型,因此不需要它。

template <typename T>
List<T>::Node::Node(T value)
{
  data = value;
  next = 0;
}

template <typename T>
List<T>::Node::~Node()
{
   --nodes_alive;
}