如何将函数作为参数传递然后执行它。我正在尝试做这样的事情:
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;
}
这当然行不通。
最佳答案
你很接近。
class Foo
{
public:
typedef void(*FN)(void);
Foo(FN fn) : fn_(fn) {};
bool Execute()
{
fn_();
return true;
}
FN fn_;
};
void pFunc(){
printf("test");
}
int main()
{
Foo foo(&pFunc);
foo.Execute();
}
关于c++ - 将 Void 作为指针传递给类,然后执行其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7421886/