我正在考虑使用模板。
就目前而言,在查看了一些指南后,我设法建立了一个功能齐全的指南,但是我想知道模板指针的目的是什么?该代码似乎是在任意使用它们。我将在下面的标题代码上举例说明:
template <class T>
class LinkedList{};
template <class T>
class LinkedList<T*>{
private:
Node<T*> *first;
int size;
public:
class Iterator{
public:
Iterator(Node<T*> *newElem){
elem = newElem;
}
virtual ~Iterator(){
}
T getValue(){
return *(elem->getValue());
}
void next(){
elem = elem->getNext();
}
void operator++(int i){
next();
}
void operator++(){
next();
}
T operator*(){
return getValue();
}
bool operator==(const Iterator& rhs){
return (elem == rhs.elem);
}
bool operator!=(const Iterator& rhs){
return (elem != rhs.elem);
}
bool hasNext(){
if (elem == NULL)
return false;
return true;
}
private:
Node<T*> *elem;
};
在此特定上下文中,为什么我们需要声明节点变量或链接列表&lt;t *>?就我而言,使用&lt;T>,但我很可能缺少一些东西。使用&lt;T>也是,当您在那里添加该指针时,实际上会发生什么?
非常感谢!
差异在于您的Node
的内容。
让我们定义Node
类:
template <class T>
struct Node
{
T data;
Node * next;
Node * previous;
};
让我们使用int
作为类型T
,并实例化:
struct Node
{
int data;
Node * next;
Node * previous;
};
让我们使用int
并实例化T *
,如Node<T*>
或Node <int *>
:
struct Node
{
int * data;
Node * next;
Node * previous;
};
请注意data
成员的数据类型有任何区别吗?
在一个示例中,data
是int
。在另一个示例中,data
是指向 int
的指针。