"Node<T*> *first"和"Node<T> *first"有什么区别?



我正在考虑使用模板。

就目前而言,在查看了一些指南后,我设法建立了一个功能齐全的指南,但是我想知道模板指针的目的是什么?该代码似乎是在任意使用它们。我将在下面的标题代码上举例说明:

template <class T>
class LinkedList{};
template <class T>
class LinkedList<T*>{
private:
    Node<T*> *first;
    int size;
public:
    class Iterator{
    public:
        Iterator(Node<T*> *newElem){
                elem = newElem;
        }
        virtual ~Iterator(){
        }
        T getValue(){
            return *(elem->getValue());
        }
        void next(){
            elem = elem->getNext();
        }
        void operator++(int i){
            next();
        }
        void operator++(){
            next();
        }
        T operator*(){
            return getValue();
        }
        bool operator==(const Iterator& rhs){
            return (elem == rhs.elem);
        }
        bool operator!=(const Iterator& rhs){
            return (elem != rhs.elem);
        }
        bool hasNext(){
            if (elem == NULL)
                return false;
            return true;
        }
    private:
        Node<T*> *elem;
    };

在此特定上下文中,为什么我们需要声明节点变量或链接列表&lt;t *>?就我而言,使用&lt;T>,但我很可能缺少一些东西。使用&lt;T>也是,当您在那里添加该指针时,实际上会发生什么?

非常感谢!

差异在于您的Node的内容。

让我们定义Node类:

template <class T> 
struct Node
{
  T data;
  Node * next;
  Node * previous;
};

让我们使用int作为类型T,并实例化:

struct Node
{
    int data;
    Node * next;
    Node * previous;
};

让我们使用int并实例化T *,如Node<T*>Node <int *>

struct Node
{
    int * data;
    Node * next;
    Node * previous;
};

请注意data成员的数据类型有任何区别吗?

在一个示例中,dataint。在另一个示例中,data指向 int的指针。

最新更新