我编写了以下代码来实现C ++中的Linked List。但我正在编译它的错误。我认为问题在于使用模板。
#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
答案 0 :(得分:3)
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;
在push
:
template<class T>
void push(node<T> **headRef ,T data){
node<T> *temp = new node<T>();
答案 1 :(得分:1)
在您编写节点的所有地方,您需要添加模板arg。
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。