C++如何实现回调?
C++ How to implement callbacks?
我正在尝试用 C++ 实现 Button
class。到目前为止的进展情况如下:
button.h:
class Button {
private:
unsigned short x;
unsigned short y;
std::string text;
std::function<void()> onClickFunction;
public:
Button(unsigned short x, unsigned short y, std::string text, std::function<void()> onClickFunction);
void onClick();
button.cpp:
Button::Button(unsigned short x, unsigned short y, std::string text, std::function<void()> onClickFunction)
{
this->x = x;
this->y = y
this->text = text;
this->onClickFunction = onClickFunction;
}
void Button::onClick()
{
this->onClickFunction();
}
但是,当我尝试创建一个按钮时,例如:
this->toggleGridButton = Button(x, y, "Toggle Grid", &Engine::toggleGrid);
我收到以下错误:
no instance of constructor "Button::Button" matches the argument list -- argument types are: (int, int, const char [12], void (Engine::*)())
如何回调成员函数?
你可能想要:
this->toggleGridButton = Button(x, y, "Toggle Grid", [this]() { this->toggleGrid(););
我正在尝试用 C++ 实现 Button
class。到目前为止的进展情况如下:
button.h:
class Button {
private:
unsigned short x;
unsigned short y;
std::string text;
std::function<void()> onClickFunction;
public:
Button(unsigned short x, unsigned short y, std::string text, std::function<void()> onClickFunction);
void onClick();
button.cpp:
Button::Button(unsigned short x, unsigned short y, std::string text, std::function<void()> onClickFunction)
{
this->x = x;
this->y = y
this->text = text;
this->onClickFunction = onClickFunction;
}
void Button::onClick()
{
this->onClickFunction();
}
但是,当我尝试创建一个按钮时,例如:
this->toggleGridButton = Button(x, y, "Toggle Grid", &Engine::toggleGrid);
我收到以下错误:
no instance of constructor "Button::Button" matches the argument list -- argument types are: (int, int, const char [12], void (Engine::*)())
如何回调成员函数?
你可能想要:
this->toggleGridButton = Button(x, y, "Toggle Grid", [this]() { this->toggleGrid(););