将Void作为指针传入类,然后执行其内容
Passing Void into a class as a pointer then executing its contents
如何传递一个函数作为参数,然后执行它。我想做这样的事情:
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();
}
尝试:
void (*external)();
你最初的声明是指向void的指针,而不是指向返回void的函数的指针。
设置为
external = function;
和execute with
external();
同时,external必须声明为函数指针void (*external)()
。否则,必须在函数指针和空指针之间进行强制转换。
相关文章:
- CMake:如何将库 A 链接到库 B,然后将可执行文件链接到库 A
- 我如何将一个变量与另一个变量进行比较,例如我想如果(var1 > var2 x 1),然后执行此 c++
- 如何从文本文件中获取值,然后用它们执行一些计算(例如乘以并显示它们)?
- 等待所有线程完成一项工作,然后执行另一项工作
- 打开一个文件,修改每个字符,然后执行反向操作不输出原始文件
- 如何在多维数组中搜索单个行,然后对某些行中的每个单个元素执行计算
- 如何在%appdata%中创建文件夹,在其中创建.bat文件,然后执行它?
- 如何对 n 个字符串执行操作,然后在C++中打印它们
- 如何使用我的 if-else 语句根据用户权重的输入执行特定操作,然后将其显示到控制台?
- 在CIN为真后,使用一段时间循环,然后执行循环
- 在服务器上执行命令,然后将结果发送到Windows中的客户端
- 如何使用循环检查等效性,然后在没有等效性的情况下执行一些代码?
- 等待buttonPressed()插槽完成,然后执行buttonRelease()
- Boost绑定和Boost函数,将带有参数的函数存储在向量中,然后执行它们
- 我有一个 c++ 代码,它在启动时崩溃,然后到达问题所在 main() 的执行
- 通过引用传递C++向量,然后执行 push_back()
- 程序正确执行,然后出现段错误
- C++ std::binary_search() 然后是 std::lower_bound() 组合是否意味着我正在执行
- 将Void作为指针传入类,然后执行其内容
- C++,Visual Studio:有可能创建一个可执行文件来设置环境变量,然后执行吗