声明为 void 的变量或字段
Variable or field declared as void
我已经阅读了大多数具有相同问题的帖子,但我在这些解决方案中没有找到我的问题。
我想使用一个简单的链表,其中包含通用内容:
但是我收到书面错误"变量或字段>>插入<<声明为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::list
或 std::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::list
或std::forward_list
,而不是推出自己的容器。没有必要重新发明轮子。
相关文章:
- 为了方便起见,我应该避免公开私有字段变量吗
- 声明为无效的变量或字段'...' Ardunio 编译器上的错误
- 错误:变量或字段'PrintEntity'声明无效无效打印实体(实体 e);
- Eclipse 编译器有没有办法将变量中的地址字段显示为整数值?
- C++ SPDLOG 编译错误:变量或字段"set_error_handler"声明为无效
- 声明为类字段而不是全局变量
- 位字段附近的变量会损坏吗?
- 带有 std::map 的模板函数给出错误:变量或字段声明为 void
- 为什么字段中的第二个变量没有更改
- 视觉错误:变量或字段'Palindrome'在 C++ 中声明为 void
- 无法汇总初始化类型结构的变量,其中包含在类模板中的位字段成员
- SSE错误 - 使用M128I_I32定义__M128i变量的字段
- 声明为无效的变量或字段'name of var'
- 声明为无效的变量或字段'Function'
- C++错误"变量或字段声明为无效"
- OpenGL彩色拾取器/变量或字段“ GlreadPixels”声明为void
- 声明为无效的变量或字段'insertion_sort' 第 13 行第 27 列
- 类指针字段,类型为变量(有点)
- 为结构的字段赋值,也更改其他变量
- 声明为 void 的变量或字段