在数组C++中保存函数指针

Save Function Pointers in Arrays C++

本文关键字:函数 指针 保存 数组 C++      更新时间:2023-10-16

我需要保存在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;

可以,但我可以推荐std::函数吗?它更容易处理更复杂的情况,例如指向类方法的指针。

下面是函数指针方式和std::函数方式的示例

#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);
}