基本上,我需要实现一个事件处理程序类,但是遇到一个错误,我无法声明一个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);
}
您能帮我弄清楚确切的语法吗?谢谢!
这不是空洞的数组。它是函数指针的数组。您应该将其定义如下:
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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句