C ++模板 - LinkedList [英] C++ Templates - 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;
}
编译时遇到错误 - error C2955:'Node ':使用类模板需要模板参数列表 - 它指向我的add方法中的下面一行代码 -
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 ::列表,虽然有时可能有点令人沮丧。
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.
这篇关于C ++模板 - LinkedList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!