C++声明函数指针数组

3

我需要实现一个事件处理程序类,但是遇到了一个错误,无法声明一个 void 类型的数组:

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 handler\n");
}
void handler2(std::string response)
{
    printf("ON_READY_EVENT handler\n");
}

void main()
{
    someClass.registerEventHandler(ON_INIT_EVENT, handler1);
    someClass.registerEventHandler(ON_READY_EVENT, handler2);
}

你能帮我弄清楚确切的语法吗?谢谢!

3个回答

11

这不是一个void数组,而是一个函数指针数组。 你应该定义为下面这样:

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;

1
此外,考虑使用 event_handler = std::function<void(std::string)> - 它将接受更多可调用对象,不仅仅是函数,还包括 lambda 表达式等。 - MSalters
...并增加了巨大的开销 - cubuspl42
3
@cubuspl42 是对的,但并非总是如此。 https://dev59.com/A2cs5IYBdhLWcg3w84hp - SGrebenkin

3
你正在将 eventHandles 定义为指向返回 5 个 void 数组的函数的指针,这不是你想要的结果。
使用 typedef 来替代尝试在一行中完成它会更加易读和方便:
typedef void (*event_handler_t)(std::string);
event_handler_t eventHandlers[TOTAL_EVENTS];

3

你混淆了事件处理程序类型和数组定义。使用 typedef 进行分离:

typedef void(*eventHandler)(std::string);
eventHandler eventHandlers[TOTAL_EVENTS];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接