c++ - “节点”有什么区别*first" 和 "节点*第一的”?
问题描述
我正在研究使用模板实现链接列表。
就目前而言,在查看了一些指南之后,我已经设法构建了一个功能正常的指南,但我想知道模板指针的目的是什么?该代码似乎任意使用它们。我将在下面举例说明我的标头代码:
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;
};
在这种特定的上下文中,为什么我们需要用<T *>声明节点变量或者链表呢?就我而言,使用 < T > 效果很好,但我很可能会遗漏一些东西。Node 类(上面未列出)也是使用 <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
并实例化 a T *
,如Node<T*>
or Node <int *>
:
struct Node
{
int * data;
Node * next;
Node * previous;
};
注意到data
成员的数据类型有什么不同吗?
在一个例子中,data
是一个int
。在另一个示例中,data
是一个指向 int
.
推荐阅读
- python - 使用 pubsub 消息启动其他 GCF 的 Google 云功能以“状态:连接错误”结尾
- html - 如何在 JQuery 中将变量从一个函数传递到另一个函数
- elasticsearch - Grafana 和 Elasticsearch:如何执行简单查询
- azure - Azure API 管理不验证负载中的必需属性
- selenium - 需要从 Web 表中选择行
- python - 无法以所需的 DateTime 格式转换时间
- swift - 如何初始化可选数组?
- python - Tkinter 按钮搞砸了一切
- c++ - 不正确的模板专业化
- c++ - 尝试使用 init() 启动我的程序,但它告诉我没有合适的默认构造函数可用