为什么我得到错误,模板参数需要'结构节点'
Why I am getting error, template argument required for ‘struct node’?
我写了下面的代码在c++中实现链表。但我得到的错误编译它。我认为问题在于模板的使用。
#include<iostream>
template<class T>
struct node{
T data;
struct node *next;
};
template<class T>
void push(struct node **headRef ,T data){
struct node *temp =(struct node*) malloc(sizeof(struct node));
temp->data=data;
temp->next=*headRef;
*headRef=temp;
}
int main(){
struct node *ll = NULL;
push(&ll,10);
push(&ll,3);
push(&ll,6);
push(&ll,8);
push(&ll,13);
push(&ll,12);
}
误差MsLL.cpp:9:18: error: template argument required for ‘struct node’
MsLL.cpp: In function ‘void push(int**, T)’:
MsLL.cpp:10:8: error: template argument required for ‘struct node’
MsLL.cpp:10:19: error: invalid type in declaration before ‘=’ token
MsLL.cpp:10:28: error: template argument required for ‘struct node’
MsLL.cpp:10:28: error: template argument required for ‘struct node’
MsLL.cpp:10:21: error: expected primary-expression before ‘struct’
MsLL.cpp:10:21: error: expected ‘)’ before ‘struct’
MsLL.cpp:11:7: error: request for member ‘data’ in ‘temp->’, which is of non-class type ‘int’
MsLL.cpp:12:7: error: request for member ‘next’ in ‘temp->’, which is of non-class type ‘int’
MsLL.cpp: In function ‘int main()’:
MsLL.cpp:16:8: error: template argument required for ‘struct node’
MsLL.cpp:16:17: error: invalid type in declaration before ‘=’ token
struct node *ll = NULL;
无效。你必须使用模板实例化语法。
struct node<int> *ll = NULL;
同样,您必须在push
中使用模板参数。
template<class T>
void push(struct node<T> **headRef ,T data){
struct node<T> *temp =(struct node<T>*) malloc(sizeof(struct node<T>));
一般性改进建议
- 您不需要使用
struct node<T>
。您可以只使用node<T>
。 - 最好使用
new
代替malloc
(delete
代替free
)。
类模板可以更新为:
template<class T>
struct node{
T data;
node *next;
};
在main
,
node<int> *ll = NULL;
In push
:
template<class T>
void push(node<T> **headRef ,T data){
node<T> *temp = new node<T>();
在你写node的所有地方,你需要添加模板参数。
template<class T>
struct node
{
T data;
struct node *next;
};
template<class T>
void push(struct node<T> **headRef ,T data){
struct node<T> *temp =(struct node<T>*) malloc(sizeof(struct node<T>));
temp->data=data;
temp->next=*headRef;
*headRef=temp;
}
您还应该使用new
而不是malloc
来确保构造函数在对象上运行,使用malloc可能会给您带来麻烦,因为它只分配了一块内存,并且不知道任何关于构造函数的信息。一般规则:在c++代码中尽量不要使用malloc
相关文章:
- 在树结构.txt文件中搜索节点
- 类成员函数无法访问同一类的私有结构节点?
- 如何在C++中实现节点数任意的通用树数据结构?
- 为什么将函数的返回类型从结构节点*更改为void后,链表的元素没有显示create_ll和显示?
- 如何在级别上打印树,给定一个结构,该结构保存节点的值及其父节点的值,对于树中的每个节点
- 无法使用类型为"结构节点 *"的左值初始化类型为"结构节点 *"的参数
- 用于基于节点的树结构的Python绑定
- 结构之外的节点 * head 有什么作用?
- 为什么树结构比其节点的总和占用更多的空间
- 如何使用指针连接两种不同的节点类型(结构)?
- lower_bound结构节点的类数组中
- C++中的数据结构,插入链表中节点的开头
- 交换树数据结构中根的 2 个子节点指针
- 如何拥有将数组保存在C 中的节点结构
- 链表类,如何访问嵌套节点结构的数据
- 节点结构调用自身
- BST 以 2d 数组作为节点结构中的键而不是 int
- 分段错误 11 链表节点结构
- 链表节点结构的第一个成员变量总是下一个节点
- 面试编码-将指向节点结构的指针作为参数,并返回传入数据结构的完整副本