C ++ LinkedList使用模板 [英] C++ LinkedList using template
本文介绍了C ++ LinkedList使用模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用模板在c ++中创建自己的链表实现。但是,我遇到了几个编译器错误。这里是代码:
I want to make my own linkedlist implementatin in c++ using templates. However, I run into several compiler errors. Here is the code:
template <class T>
class Node{
T datum;
Node _next = NULL;
public:
Node(T datum)
{
this->datum = datum;
}
void setNext(Node next)
{
_next = next;
}
Node getNext()
{
return _next;
}
T getDatum()
{
return datum;
}
};
template <class T>
class LinkedList{
Node<T> *node;
Node<T> *currPtr;
Node<T> *next_pointer;
int size;
public:
LinkedList(T datum)
{
node = new Node<T>(datum);
currPtr = node; //assignment between two pointers.
size = 1;
}
void add(T datum)
{
Node<T> *temp = new Node<T>(datum);
(*currPtr).setNext((*temp));
currPtr = temp;
size++;
}
T next()
{
next_pointer = node;
T data = (*next_pointer).getDatum();
next_pointer = (*next_pointer).getNext();
return data;
}
int getSize()
{
return size;
}
};
当我尝试实例化这个类时,出现以下错误:
when I try to instantiate this class, I got the following errors:
LinkedList.cpp: In instantiation of `Node<int>':
LinkedList.cpp:35: instantiated from `LinkedList<T>::LinkedList(T) [with T = int]'
LinkedList.cpp:60: instantiated from here
LinkedList.cpp:7: error: `Node<T>::_next' has incomplete type
LinkedList.cpp:5: error: declaration of `class Node<int>'
make[2]: *** [build/Debug/Cygwin-Windows/LinkedList.o] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2
我正在使用NetBeans IDE。有人可以给我一些改进它的建议吗?非常感谢!
I'm using NetBeans IDE. Could anybody give me some suggestion to improve it? Thanks a lot!!
推荐答案
就像你做 Node< T> *节点;
在 LinkedList
中,您还需要在 Node
class
Just like when you do Node<T> *node;
in the LinkedList
, you need to also do the same in your Node
class
template <class T>
class Node{
T datum;
Node<T> *_next;//template parameter
//also, need to make this a pointer and initialized in constructor
public:
//...
void setNext(Node<T> next) //template parameter
{
_next = next;
}
Node<T> getNext() //template parameter
{
return _next;
}
//...
};
这篇关于C ++ LinkedList使用模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文