我正在做一个关于双向链表的程序。我有函数 find
可以帮助定位,如果本身没有。 7 在该列表中的任何位置。此函数工作正常并返回指向该节点的指针。
然后我有函数 afterElement
插入例如 no。 3号后7, 所以它使用指向find
函数的指针作为参数。我认为这就是问题的根源,但我可能是错的,你来判断。
我想知道如何正确使用这个功能?我传递参数的方式有问题吗? 我得到的错误是“没有上下文类型信息的重载函数”。
相关代码如下:
#include <iostream>
using namespace std;
struct node {
int data;
node* prev;
node* next;
};
node* find(int,node*&);
void afterElement(int,int,node*&,node*&,node* (*find)(int, node*&));
int main() {
node* head = NULL;
node* tail = NULL;
// The program itself has a menu that allows for input of value in list but
// for the sake of relevancy and shortness of code I dropped it out from here
int x, y;
cout << "Insert 2 values: value you wish to insert, and value you wish to insert it after. ";
cin >> x;
cin >> y;
afterElement(x,y,head,tail,(*find)(y,head)); // here is the error "overloaded function..."
return 0;
}
node* find(int x,node*& head) {
node* curr = head;
while ((curr != NULL) && (curr->data != x))
curr = curr->next;
return curr;
}
void afterElement(int x,int after,node*& head,node*& tail,node* (*find)(int x, node*& head)) {
node* N;
node* compared = (*find)(after,head);
N->data = x;
if (compared == NULL)
cout << "There is no element " << after << " in the list!\n";
else {
if (compared->next == NULL) {
compared->next = N;
N->prev = compared;
N->next = NULL;
tail = N;
} else {
compared->next->prev = N;
N->next = compared->next;
compared->next = N;
N->prev = compared;
}
}
}
最佳答案
如果你想将一个函数作为参数传递给另一个函数,你只需要使用函数名,而不是整个调用表达式。
afterElement(x,y,head,tail,find);
这是导致您的程序编译的最小修复。 Live demo .请注意,这仅表明编译错误已修复,而不是程序正常运行!
此外,因为您正在using namespace std
,您会收到无法理解的错误消息,因为编译器无法弄清楚您想要的是什么find
,是您自己的还是标准::查找
。如果您摆脱了 using namespace std
,您的错误消息将变得更加清晰:
error: cannot convert ‘node*’ to ‘node* (*)(int, node*&)’
Live demo .切勿使用 using namespace std
。
但是您可能需要考虑从 afterElement
的参数列表中删除 find
。 afterElement
不需要被告知要调用哪个函数来查找元素。
void afterElement(int x,int after,node*& head,node*& tail)
会工作得很好。
传递一个指向节点的指针而不是 int after
也可以工作:
void afterElement(int x, node* after, node*& head, node*& tail)
调用 afterElement(x, y, find(x, head), head, tail)
以使用此变体。请注意,您不需要说 (*find)(x, head)
。
您的代码存在的问题比这个编译错误还多。例如
node* N;
...
N->data = x;
不正确。你还没有初始化 N
,它没有指向任何地方,所以你不能在它上面使用 ->
。
另一个问题是您的程序从不修改head
,因此列表没有机会包含任何内容。这也许应该通过添加更多功能来解决(可能像 beforeElement
)。
关于c++ - 如何解决没有上下文类型信息错误的重载函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55355715/