我正在做一个关于双向链表的程序。我有功能find
,如果有的话,它可以帮助您定位。 7在该列表中的任何位置。此函数可以正常工作,并返回指向该节点的指针。
然后我有一个函数afterElement
,例如插入编号。 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;
}
}
}
答案 0 :(得分:0)
我发现您想将“ find”功能作为参数传递给afterElement函数。
确定可以将一个函数作为参数传递给其他函数。函数也存储在存储位置中。该存储位置存储在与函数名称相同的变量中(在本例中为“ find”)。
现在,您将在afterElement函数中将find函数参数作为指针接收,因此它需要一个地址,但是您正在传递整个函数。这就是它给出编译错误的原因。 正确的代码如下:
this.router.navigate(['/'], { fragment: 'top' });
我已经检查了编译情况,但是请检查一次您期望的结果。 谢谢。
答案 1 :(得分:0)
如果要将一个函数作为参数传递给另一个函数,则只需要使用函数名,而不是整个调用表达式即可。
afterElement(x,y,head,tail,find);
这是导致您的程序编译的最小修复。 Live demo。请注意,这仅表明编译错误已得到解决,而不能证明程序可以正常工作!
此外,由于您是using namespace std
,因此您将收到难以理解的错误消息,因为编译器无法确定您想到的find
是您自己还是std::find
。如果您摆脱了using namespace std
,您的错误消息就会更加清晰:
error: cannot convert ‘node*’ to ‘node* (*)(int, node*&)’
Live demo。永远不要使用using namespace std
。
但是,您可能要考虑从find
的参数列表中删除afterElement
。无需告知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
)来解决此问题。