【问题标题】:C++ Declaring An Array Of Function PointersC++ 声明一个函数指针数组
【发布时间】:2015-02-05 18:25:28
【问题描述】:

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

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

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

【问题讨论】:

    标签: c++


    【解决方案1】:

    这不是空数组。它是函数指针数组。 您应该将其定义如下:

    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;
    

    【讨论】:

    • 另外,考虑using event_handler = std::function&lt;void(std::string)&gt; - 它将接受更多的可调用对象,不仅是函数,还包括 lambda 表达式等。
    • ...并增加了巨大的开销
    • @cubuspl42 是的。但不总是。 stackoverflow.com/questions/12452022/…
    【解决方案2】:

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

    与其尝试在一行中执行此操作,不如使用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];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-16
        • 1970-01-01
        • 1970-01-01
        • 2010-11-20
        • 1970-01-01
        • 2010-09-25
        • 2011-06-20
        • 1970-01-01
        相关资源
        最近更新 更多