【发布时间】:2019-08-16 18:02:34
【问题描述】:
我正在做一个关于双向链表的程序。我有功能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()函数而不是从中调用find()函数?以及将指针作为函数参数的引用......为什么? -
afterElement有一个函数指针作为它的最后一个参数,但是你传递了一个指向节点的指针,即调用find的结果:(*find)(y,head)调用函数,如果你想传递函数只需使用&find作为值参数。
标签: c++ c++11 compiler-errors linked-list arguments