C++声明函数指针数组
C++ Declaring An Array Of Function Pointers
基本上我需要实现一个事件处理程序类,但遇到了一个错误,我无法声明一个空数组:
class SomeClass
{
public:
void registerEventHandler(int event, void (*handler)(std::string));
private:
// here i get this error: declaration of ‘eventHandlers’ as array of void
void (*eventHandlers)(std::string)[TOTAL_EVENTS];
}
void SomeClass::registerEventHandler(int event, void (*handler)(std::string))
{
eventHandlers[event] = handler;
}
void handler1(std::string response)
{
printf("ON_INIT_EVENT handlern");
}
void handler2(std::string response)
{
printf("ON_READY_EVENT handlern");
}
void main()
{
someClass.registerEventHandler(ON_INIT_EVENT, handler1);
someClass.registerEventHandler(ON_READY_EVENT, handler2);
}
你能帮我弄清楚确切的语法吗?谢谢
这不是空洞的数组。它是函数指针数组。您应该定义如下:
void (*eventHandlers[TOTAL_EVENTS])(std::string);
或者更好(C++14):
using event_handler = void(*)(std::string);
event_handler handlers[TOTAL_EVENTS];
或C++03:
typedef void(*event_handler)(std::string);
event_handler handlers[TOTAL_EVENTS];
但我更建议使用矢量:
using event_handler = void(*)(std::string);
std::vector<event_handler> handlers;
您将eventHandles
定义为返回5个void
s数组的函数的指针,这不是您想要的。
与其试图在一行中完成这项工作,不如使用typedef
:来更容易、更可读
typedef void (*event_handler_t)(std::string);
event_handler_t eventHandlers[TOTAL_EVENTS];
您混合了事件处理程序类型和数组定义。用typedef:分隔
typedef void(*eventHandler)(std::string);
eventHandler eventHandlers[TOTAL_EVENTS];
相关文章:
- 添加到数组指针
- C++语法差异:二维和一维数组(指针算术)
- 数组指针表示法C++(移动数组时)
- 复制后删除原始数组指针将前 3 个字节设置为 0
- C++访问指向结构的指针中的类数组指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 创建<int>对整数数组指针的矢量引用 (C++)
- 将 2D 数组指针传递给 C++ 中的函数
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 队列数组指针 (C++)
- C++数组指针上的删除操作
- 对于循环不循环和检测字符数组 [指针和字符数组]
- 如何初始化数组指针对象
- 如何正确传递 2D 数组指针作为参数
- 从数组指针中获取怪异的数字
- 初始化std :: unique_ptr作为原始数组指针的初始化
- 将结构数组指针从C#传递到C
- STD :: Sort将数组指针设置为NULL
- C++数组指针错误无法将“int*”转换为“int**”