基本上我需要实现一个事件处理程序类,但遇到一个错误,我不能声明一个空洞数组:
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);
}
Run Code Online (Sandbox Code Playgroud)
你能帮我弄清楚确切的语法吗?谢谢!
SGr*_*kin 10
这不是空洞的数组.它是函数指针的数组.您应该按如下方式定义它:
void (*eventHandlers[TOTAL_EVENTS])(std::string);
Run Code Online (Sandbox Code Playgroud)
或者更好(C++ 14):
using event_handler = void(*)(std::string);
event_handler handlers[TOTAL_EVENTS];
Run Code Online (Sandbox Code Playgroud)
或者C++ 03:
typedef void(*event_handler)(std::string);
event_handler handlers[TOTAL_EVENTS];
Run Code Online (Sandbox Code Playgroud)
但我宁愿建议使用矢量:
using event_handler = void(*)(std::string);
std::vector<event_handler> handlers;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1879 次 |
| 最近记录: |