基本上我需要实现一个事件处理程序类,但遇到无法声明空数组的错误:
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);
}
你能帮我弄清楚确切的语法吗? 谢谢!
最佳答案
这不是空数组。它是函数指针数组。 您应该按如下方式定义它:
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;
关于C++ 声明一个函数指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28341154/