【发布时间】:2016-05-13 00:18:22
【问题描述】:
我需要保存在数组中的方法指针,像这样:
int main() {
void* man[10];
man[0]= void* hello();
man[0](2);
}
void hello(int val){
}
问题是,我能做到吗?
谢谢
【问题讨论】:
标签: c++ arrays function-pointers
我需要保存在数组中的方法指针,像这样:
int main() {
void* man[10];
man[0]= void* hello();
man[0](2);
}
void hello(int val){
}
问题是,我能做到吗?
谢谢
【问题讨论】:
标签: c++ arrays function-pointers
是的,您可以通过创建函数指针数组轻松实现此目的。如果你先给函数类型起别名,这将是最易读的:
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;
【讨论】:
using... 可能还需要几年时间,我才能记住我能做到这一点。
是的,你可以,但是may I recommend std::function? 它可以更轻松地处理更复杂的情况,例如指向类方法的指针。
下面是函数指针方式和 std::function 方式的示例:
#include <iostream>
#include <functional> // for std::function
//typedef void (*funcp)(int); // define a type. This makes everything else way, way easier.
//The above is obsolete syntax.
using funcp = void(*)(int); // Welcome to 2011, monkeyboy. You're five years late
void hello(int val) // put the function up ahead of the usage so main can see it.
{
std::cout << val << std::endl;
}
int main()
{
funcp man[10];
man[0]= hello;
man[0](2);
std::function<void(int)> man2[10]; // no need for typdef. Template takes care of it
man2[0] = hello;
man2[0](3);
}
【讨论】:
typedef 在 C++ 中确实过时了。 using 是一个更强大、更易读的替代方案。