[英]Why I am getting error, template argument required for ‘struct node’?
我編寫了以下代碼以在C ++中實現鏈接列表。 但是我在編譯它時遇到了錯誤。 我認為問題在於使用Template。
#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參數。
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>();
在所有寫入節點的地方都需要添加模板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可能會讓您感到悲傷,因為malloc只是分配了一塊內存,並且對構造函數一無所知。 如果可以避免,一般規則不要在C ++代碼中使用malloc。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.