我需要在 Arrays 中保存方法指针,像这样:
int main() {
void* man[10];
man[0]= void* hello();
man[0](2);
}
void hello(int val){
}
问题是,我能做到吗?
谢谢
最佳答案
是的,您可以通过创建函数指针数组轻松实现这一点。如果您首先为函数类型起别名,那么这是最易读的:
void hello(int);
void world(int);
int main()
{
using fn = void(int);
fn * arr[] = { hello, world };
}
用法:
fn[0](10);
fn[1](20);
如果没有单独的别名,语法会有点麻烦:
void (*arr[])(int) = { hello, world };
或者:
void (*arr[2])(int);
arr[0] = hello;
arr[1] = world;
关于c++ - 将函数指针保存在数组 C++ 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37199400/