转换为模板类(节点)

Converting to template class (NODES)

本文关键字:节点 转换      更新时间:2023-10-16
template <class Type>
class Node
{
public:
        Node ()
        {
        }
        Node (Type x, Node* nd)
        {
             data = x;
             next = nd;
        }
        Node (Type x)
        {
            data = x;
            next = NULL;
        }
        ~Node (void)
        {
        }
        Node (const Node* & nd)
        {
            data = nd->data;
            next = nd->next;
        }
        Node & Node::operator = (const Node* & nd)
        {
            data = nd->data;
            next = nd->next;
        }
        T data;
        Node* next;

};

我是否将每个节点* 替换为

Node*<Type>

我尝试更换它并尝试运行类似的东西

Node* temp = myq.head;

但它说类模板"节点"的参数列表丢失。当我需要 Node 类本身成为模板的一部分时,我不确定如何使用模板

Node 的每个声明都需要一个 <> 类型。

Node* temp = myq.head;

这取决于myq.head的定义。如果它被定义为 Node<int>*,那么 temp 也必须定义为 Node<int>* temp。您始终必须具有模板对象的<>。

如果你想在不知道类型的情况下拥有 Node*,你可以使用继承。具有从非模板 Node 类继承的模板化 TypedNode 类。您将能够使用 Node* 传递所有这些 TypeNode<> 对象,但在不知道节点类型的情况下,您将无法获取节点的值。

我不建议这样做,但是如果您真的想制作具有混合类型的节点列表,则需要通过以下方式跟踪类型

  1. 在基类中包含一个枚举类型,该类型定义存储在节点中的类型,并为每个类定义 typedNode,在其构造函数中设置枚举,或从虚拟方法返回枚举。
  2. RTTI,运行时类型信息 http://en.wikipedia.org/wiki/Run-time_type_information