C ++声明一组函数指针

时间:2015-02-05 10:07:58

标签: c++

基本上我需要实现一个事件处理程序类,但遇到一个我无法声明空洞数组的错误:

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 个答案:

答案 0 :(得分:10)

这不是空洞的数组。它是函数指针的数组。 您应该按如下方式定义它:

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];

但我宁愿建议使用vector:

using event_handler = void(*)(std::string);
std::vector<event_handler> handlers;

答案 1 :(得分:3)

您将eventHandles定义为指向函数的指针,该函数返回5 void的数组,这不是您想要的。

不是尝试在一行中执行此操作,而是使用typedef更容易,更易读:

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

答案 2 :(得分:3)

您混合了事件处理程序类型和数组定义。与typedef分开:

typedef void(*eventHandler)(std::string);
eventHandler eventHandlers[TOTAL_EVENTS];
相关问题