在数组C++中保存函数指针
Save Function Pointers in Arrays C++
我需要保存在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);
}
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针