声明为 void 的变量或字段

Variable or field declared as void

本文关键字:字段 变量 void 声明      更新时间:2023-10-16

我已经阅读了大多数具有相同问题的帖子,但我在这些解决方案中没有找到我的问题。

我想使用一个简单的链表,其中包含通用内容:

但是我收到书面错误"变量或字段>>插入<<声明为void"这适用于除主要方法之外的每种方法。

希望你能帮到我,谢谢

#include<iostream>
#include<string>
//EDIT:#include"liste.t" this is waste from a former test
using namespace std;

template <typename T>
struct Element{
    T value;
    Element *next;    
    Element(T v, Element *n) : value(v), next(n)
    { }  
};


template <typename T>
void insert(Element, T, int (*eq)(T,T));
template <typename T>
void remove(Element, T, int (*eq)(T,T));
void print(Element);
template <>
int equal<string>(T, T);
template <typename T>
int equal(T, T);


int main(){    
  int (*eq)(int,int) = equal;
  Element* head=NULL;
  insert(head, 2, eq);
  insert(head, 5, eq);
  insert(head, 1, eq);
  print(head);
  remove(head, 2, eq);
  print(head);
}

template <typename T>
void insert(Element* &rp, T v, int (*eq)(T, T)){
  if(rp!=NULL){
    if(eq(rp->value, v)>=0){ 
      rp = new Element(v, rp);
    }else{
      insert(rp->next, v, eq)
    }
  }else{
    rp = new Element(v, NULL);
  }  
}
 template <typename T>
 void remove(Element * &rp, T v, int (*eq)(T, T)){
   if(rp!=NULL){
     if(eq(rp->value, v)==0){//v 
       Element *tmp = rp;
       rp=rp->next;
       delete tmp;
       remove(rp,v, eq);     
     }else{
       remove(rp->next, v, eq);
     }
   }  
 }
 void print(Element *p){
   while(p){
     cout<<p->value << " ";
     p=p->next;
   }
   cout << endl;
 }

 template <>
 int equal<string>(T a, T b){
   int min=0;
   if(length(a)<length(b)){
     min = length(a);
   }else{
     min=length(b);
   }
   for(int i=0; i< min; i++){
     if(a[i]<b[i])
       return -1;
     if(a[i]>b[i])
       return 1;
   }
   return 0;
 }

 template <typename T>
 int equal(T a, T b){
   if(a<b)
     return -1;  
   if(a>b)
     return 1;
   return 0;  
 }

注意:您可能应该使用 std::liststd::forward_list,而不是推出自己的容器。

在函数声明中,使用没有模板参数的 Element 时会遇到编译错误(这可能是您询问的错误):

template <typename T>
void insert(Element, T, int (*eq)(T,T));
            ^

这应该改用Element<T>,并且还应该接受指向元素的指针。

template <typename T>
void insert(Element<T>*, T, int (*eq)(T,T));

print函数还需要是一个模板:

template <typename T>
void print(Element<T> *p)

您似乎也在尝试使用模板专用化来专门化字符串的等于。声明应为:

template <>
int equal<string>(string, string);

因为在此上下文中未声明 T。

我需要再次强调,您应该真正考虑使用std::liststd::forward_list,而不是推出自己的容器。没有必要重新发明轮子。