*第一的”?,c++,pointers,templates"/>

首页 > 解决方案 > “节点”有什么区别*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;

    };

在这种特定的上下文中,为什么我们需要用<T *>声明节点变量或者链表呢?就我而言,使用 < T > 效果很好,但我很可能会遗漏一些东西。Node 类(上面未列出)也是使用 <T> 实现的,那么当您在其中添加该指针时实际发生了什么?

非常感谢!

标签: c++pointerstemplates

解决方案


不同之处在于您的Node.

让我们定义Node类:

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

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

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

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

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

注意到data成员的数据类型有什么不同吗?

在一个例子中,data是一个int。在另一个示例中,data是一个指向 int.


推荐阅读