指向模板类对象的指针

Pointer to template class object

本文关键字:对象 指针      更新时间:2023-10-16

我正试图用模板化的值创建一个单独的List,但不幸的是,我无法用模板从我的List链接到ListElements。

在我的main中,我调用List<int> list1;来创建类List的一个实例。List包含多个ListElement,这些ListElement包含应模板化的值。

编译器在上抛出错误

ListElement* first;
ListElement* last;

在List.h中。它说C2955-"ListElement":类类型的使用需要类型参数列表

List.h

#pragma once
#include <string>
#include "ListElement.h"
template<class T>
class List
{
private:
    ListElement* first;
    ListElement* last;
public:
    List();
    ~List();
    void printList();
    void pushBack(T value);
    void pushFront(T value);
};

List.cpp

#include <iostream>
#include "List.h"
template<class T>
List<T>::List()
{
    first = NULL;
    last = NULL;
}
template<class T>
List<T>::~List()
{
}
template<class T>
void List<T>::pushBack(T value)
{
    if (last)
    {
        ListElement* tmp = last;
        last = new ListElement(value);
        last->setPrev(tmp);
        tmp->setNext(last);
    }
    else
    {
        first = new ListElement(value);
        last = first;
    }
}
template<class T>
void List<T>::pushFront(T value)
{
    if (first)
    {
        ListElement* tmp = first;
        first = new ListElement(value);
        first->setNext(tmp);
        tmp->setPrev(first);
    }
    else
    {
        last = new ListElement(value);
        first = last;
    }
}
template<class T>
void List<T>::printList()
{
    if (first)
    {
        ListElement* tmp = first;
        while (tmp)
        {
            std::cout << tmp->getValue() << std::endl;
            if (tmp != last)
                tmp = tmp->getNext();
            else
                break;
        } 
    }
    else 
    {
        std::cout << "List is empty!" << std::endl;
    }
}
template class List<int>;
template class List<std::string>;

ListElement.h

#pragma once
#include <string>
template<class T>
class ListElement
{
private:
    ListElement* next;
    ListElement* prev;
    T value;
public:
    ListElement(T val);
    ~ListElement();
    ListElement* getNext() { return next; }
    ListElement* getPrev() { return prev; }
    void setNext(ListElement* elem) { next = elem; }
    void setPrev(ListElement* elem) { prev = elem; }
    T getValue() { return value; }
};

ListElement.cpp

#include "ListElement.h"
template<class T>
ListElement<T>::ListElement(T val)
{
    value = val;
}
template<class T>
ListElement<T>::~ListElement()
{
}
template class ListElement<int>;
template class ListElement<std::string>;

ListElement是一个模板,因此您希望为指针使用一个特定的实例化:

template<class T>
class List
{
private:
    ListElement<T>* first;
    ListElement<T>* last;
    // note:   ^^^

对于其他情况也是如此。只有在模板中,模板名称才可用于当前实例化,即List中,可以使用List作为List<T>的快捷方式。