问题描述
如何将函数指针作为带有参数的参数传递?
void A(){
std::cout << "hello" << endl;
}
void B(void (*ptr)()){ // function pointer as agrument
ptr(); // call back function "ptr" points.
}
void C(string name){
std::cout << "hello" << name << endl;
}
void D(void (*ptr2)(string name)){ // function pointer as agrument
ptr2(name); // error 1
}
int main(){
void (*p)() = A; // all good
B(p); // is callback // all good
void (*q)(string name) = C;
D(q)("John Doe"); // error 2
return 0;
};
错误:
1-使用未声明的标识符'name'
2-称为“ void”的对象类型不是函数或函数指针
解决方法
您应该使D
带有两个参数,一个参数用于函数指针,一个参数用于传递给函数指针的参数。例如
void D(void (*ptr2)(string),const string& name){
ptr2(name);
}
然后称呼它
D(q,"John Doe");
,
-
name
是ptr2
类型声明的一部分,不是D
中的变量。 - 您正在尝试调用
D
从void
返回的内容。,
用于在C ++中分隔参数。
尝试一下:
#include <iostream>
#include <string>
using std::endl;
using std::string;
void A(){
std::cout << "hello" << endl;
}
void B(void (*ptr)()){ // function pointer as agrument
ptr(); // call back function "ptr" points.
}
void C(string name){
std::cout << "hello" << name << endl;
}
void D(void (*ptr2)(string name),string name){ // function pointer and a string as agrument
ptr2(name);
}
int main(){
void (*p)() = A; // all good
B(p); // is callback // all good
void (*q)(string name) = C;
D(q,"John Doe"); // pass 2 arguments
return 0;
} // you don't need ; here