如何在头文件中实现的构造函数中将指向模板类的链表指针初始化为NULL

How to initialize pointers in a linked list to templated class to NULL in constructor implemented in header file

本文关键字:NULL 链表 初始化 指针 文件 实现 构造函数      更新时间:2023-10-16

你好,我正在做一个数据结构项目,我被卡住了。该项目将构建一个模板化的链表类和一个嵌套的迭代器类,仅在头文件中。我不明白如何在模板化的LinkedList类中使用迭代器类。我对一般的迭代器不太确定。声明的方法都是运行将要运行的测试所必需的。我目前被困在初始化'LinkedList* prev'和下一步的构造函数。请帮助!如何初始化模板化的东西?编译器想知道我认为什么数据类型?谢谢你的宝贵时间错误出现在LinkedList类的构造函数声明中"从'int'类型的右值初始化'std::basic_string char&'类型的非const引用无效"是错误消息

#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
template <typename T> class  LinkedList
{
    private:
        LinkedList<T>* head;
        int size;
        T element = NULL;
        LinkedList<T>* prev;
        LinkedList<T>* next;
    public:

        class Iterator
        {
                friend class LinkedList<T>;
            private:
            public:
                Iterator();
                T operator*() const;
                Iterator& operator++();
                bool operator==(Iterator const& rhs);
                bool operator!=(Iterator const& rhs);
        };
        LinkedList<T>():prev(0), next(0){} //HERE is the ERROR????////////
        Iterator begin() const
        {
 //         Iterator tempIterator = LinkedList<T>();
//
//          return tempIterator->front;
            return NULL;
        }
        Iterator end() const{return NULL;}
        bool isEmpty() const;
        T getFront() const;
        T getBack() const;
        void enqueue(T newElement)
        {
            LinkedList<T>* newElem = new LinkedList<T>();
            newElem->element = newElement;
            if(front == 0)
            {
                front = newElem;
            }
            else
            {
                 back->next = newElem;
            }
            back = newElem;
            listSize++;
         }
        void dequeue()
        {
            LinkedList<T>* tempElem = new LinkedList<T>();
            if(front == 0){
                cout << "List is empty!" << endl;
            }
            else
            {
                tempElem = front;
                front = front->next;
                cout << "the element dequeued: " << tempElem->element;
                delete tempElem;
            }
        }
        void pop();
        void clear();
        bool contains(T element) const;
        void remove(T element);
    };


#endif /* LINKEDLIST_H_ */

构造函数语法错误。

LinkedList():prev(0), next(0){}

这是正确的构造函数语法。一旦声明了template类和参数,在template声明中,仅模板的名称(不含参数)在其作用域中引用模板本身。类似地,如果要显式定义析构函数,则为:

~LinkedList() { /* ... */ }

如果你只想在模板声明中声明构造函数:

 LinkedList();

,然后在模板声明之外定义它,那么正确的语法是:

template<typename T>
LinkedList<T>::LinkedList() :prev(0), next(0){}