如何在 c++ linux 中创建事件处理程序
How to create EventHandler in c++ linux
我想将自定义事件处理程序创建到一个类中并传递另一个类的函数。
class EventArgs
{
};
class one
{
public:
typedef void(EventHandler)(EventArgs* e);
void RegisterFunction(EventHandler* f);
private:
list<EventHandler*>function_list;
};
class two
{
public:
two();
private:
void FunctionEvent(EventArgs* e);
};
two::two()
{
one on;
on.RegisterFunction(&FunctionEvent);
}
错误代码为:没有匹配函数来调用"one::RegisterFunction(void (two::( EventArgs(("打开。RegisterFunction(&FunctionEvent(;
如果 FunctionEvent(( 它不属于第二类,就像这样工作:
void FunctionEvent(EventArgs* e)
{
}
int main()
{
one on;
on.RegisterFunction(&FunctionEvent);
}
有什么区别?
在所有情况下使其工作的最简单和最通用的方法是使用 std::function
。它非常易于使用,并且就像常规功能一样工作。此外,std::function
与 lambads、函数指针一起使用,当与 std::bind
一起使用时,它甚至可以与成员函数一起使用。
对于您的特定情况,我们希望EventHandler
函数接受EventArgs*
并且不返回任何内容:
using EventHandler = std::function<void(EventArgs*)>;
从 lambda 或函数指针创建它真的很容易:
// Create it from a lambda
EventHandler x = [](EventArgs* args) { /* do stuff */ };
void onEvent(EventArgs* args) {}
EventHandler y = &onEvent; // Create it from function pointer
此外,您可以使用 std::bind
从成员函数创建它:
// Create it from a member function
struct MyHandler {
void handleEvent(EventArgs* args);
};
MyHandler handler;
EventHandler z = std::bind(&MyHandler::handleEvent, handler);
重写类
class one
{
public:
// Use std::function instead of function pointer
using EventHandler = std::function<void(EventArgs*)>;
// Take the function by value, not by pointer.
void RegisterFunction(EventHandler f);
private:
// Store the function by value, not pointer
list<EventHandler>function_list;
};
class two
{
public:
two();
private:
void FunctionEvent(EventArgs* e);
};
two::two()
{
one on;
on.RegisterFunction(std::bind(&two::FunctionEvent, this));
}
相关文章:
- WMI检测进程创建事件-c++
- 给定顺序中的事件处理
- 如何创建事件驱动的 SDL2 应用程序
- C++事件系统 - 多态事件和事件处理程序
- wxWidgets 拖放文件事件处理程序初始化问题(无效static_cast)
- 更好的事件处理机制?
- 如何将IEnumerable与Process.Start的输出事件处理程序一起使用?
- "动态创建的事件处理程序"复选框
- Wxwidgets - 如何添加调整大小事件处理程序以使"X"绘图随窗口调整大小?
- Qt 键按事件处理程序仅在按下 ctrl、alt 或 shift 键时做出反应
- 类成员作为 C++ 中 C 样式事件的事件处理程序
- C 设计事件处理程序类
- 将托管事件处理程序传递给 Linux 中的非托管代码
- 如何在 c++ linux 中创建事件处理程序
- 指纹读取器 - 从 C# 代码创建事件处理程序到C++的问题
- 窗口创建错误 - 可能是事件处理
- 如何在从主窗口事件处理程序调用后在子窗口中创建按钮
- 尝试使用重载运算符创建新的事件处理程序>>迷失了自己试图找出所需的语法
- qt4:覆盖UI编辑器创建的小部件的事件处理程序方法
- c++事件的创建和处理