将 Void 作为指针传递到类中,然后执行其内容
如何将函数作为参数传递然后执行它。我正在尝试做这样的事情:
class Foo{
private:
void (*external);
public:
Foo(void (*function)()){ *external = *function; }
~Foo(){ }
bool Execute(){
*external(); // Somehow execute 'external' which does the same thing with 'function'
return true
}
};
void pFnc(){
printf("test");
}
int main(){
Foo foo = Foo(&pFnc);
foo.Execute();
return 0;
}
这当然是行不通的。
How can I pass a function as an argument and then execute it. I'm trying to do something like this:
class Foo{
private:
void (*external);
public:
Foo(void (*function)()){ *external = *function; }
~Foo(){ }
bool Execute(){
*external(); // Somehow execute 'external' which does the same thing with 'function'
return true
}
};
void pFnc(){
printf("test");
}
int main(){
Foo foo = Foo(&pFnc);
foo.Execute();
return 0;
}
This is not working of course.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你很接近。
You were close.
尝试:
您的原始声明是指向 void 的指针,而不是指向返回 void 的函数的指针。
Try:
Your original declaration is a pointer to void, not a pointer to a function returning void.
设置它
并执行 with
另外,external 必须声明为函数指针
void (*external)()
。否则,您必须在函数指针和 void 指针之间进行转换。Set it with
and execute with
Also, external has to be declared as a function pointer
void (*external)()
. Otherwise, you have to cast between function- and void-pointer.