C++ 模板 - LinkedList
编辑 - 在下面回答,错过了尖括号.谢谢大家.
EDIT -- Answered below, missed the angled braces. Thanks all.
我一直在尝试编写一个基本的单向链表,我可以在其他程序中使用它.我希望它能够使用内置和用户定义的类型,这意味着它必须被模板化.
I have been attempting to write a rudimentary singly linked list, which I can use in other programs. I wish it to be able to work with built-in and user defined types, meaning it must be templated.
因此,我的节点也必须被模板化,因为我不知道它要存储的信息.我写了一个节点类如下 -
Due to this my node must also be templated, as I do not know the information it is going to store. I have written a node class as follows -
template <class T> class Node
{
T data; //the object information
Node* next; //pointer to the next node element
public:
//Methods omitted for brevity
};
我的链表类是在单独的类中实现的,在链表末尾添加新节点时需要实例化一个节点.我已按如下方式实施 -
My linked list class is implemented in a seperate class, and needs to instantiate a node when adding new nodes to the end of the list. I have implemented this as follows -
#include <iostream>
#include "Node.h"
using namespace std;
template <class T> class CustomLinkedList
{
Node<T> *head, *tail;
public:
CustomLinkedList()
{
head = NULL;
tail = NULL;
}
~CustomLinkedList()
{
}
//Method adds info to the end of the list
void add(T info)
{
if(head == NULL) //if our list is currently empty
{
head = new Node<T>; //Create new node of type T
head->setData(info);
tail = head;
}
else //if not empty add to the end and move the tail
{
Node* temp = new Node<T>;
temp->setData(info);
temp->setNextNull();
tail->setNext(temp);
tail = tail->getNext();
}
}
//print method omitted
};
我已经设置了一个驱动程序/测试类如下 -
I have set up a driver/test class as follows -
#include "CustomLinkedList.h"
using namespace std;
int main()
{
CustomLinkedList<int> firstList;
firstList.add(32);
firstList.printlist();
//Pause the program until input is received
int i;
cin >> i;
return 0;
}
我在编译时遇到错误 - 错误 C2955:'节点':使用类模板需要模板参数列表 - 这将我指向我的添加方法中的以下代码行 - >
I get an error upon compilation however - error C2955: 'Node' : use of class template requires template argument list - which points me to the following line of code in my add method -
Node* temp = new Node<T>;
我不明白为什么这没有关于类型的信息,因为它在我的驱动程序类中创建时被传递到链表.我应该怎么做才能将类型信息传递给 Node???strong>
I do not understand why this has no information about the type, since it was passed to linked list when created in my driver class. What should I be doing to pass the type information to Node?
我应该创建一个私有节点结构而不是一个单独的类,并将两个类的方法合并到一个文件中吗?我不确定这会克服这个问题,但我认为它可能会.如果可能的话,我宁愿单独上课.
Should I create a private node struct instead of a seperate class, and combine the methods of both classes in one file? I'm not certain this would overcome the problem, but I think it might. I would rather have seperate classes if possible though.
谢谢,安德鲁.
推荐答案
可能想试试
Node<T>* temp = new Node<T>;
此外,要获得有关如何设计列表的提示,您当然可以查看 std::list,尽管它有时会令人生畏.
Also, to get hints on how to design the list, you can of course look at std::list, although it can be a bit daunting at times.
相关文章