C++ 如何实现回调?

时间:2021-01-12 23:52:54

标签: c++ callback

我正在尝试用 C++ 实现一个 Button 类。到目前为止的情况如下:

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);

我收到以下错误:

<块引用>

没有构造函数“Button::Button”的实例匹配参数列表——参数类型是:(int, int, const char [12], void (Engine::*)())

如何回调成员函数?

1 个答案:

答案 0 :(得分:1)

您可能想要:

vector1: p7d_A1    p7d_A2     p7d_A3 
        "random"  "random"   "random"

vector2: p7d_A1   p7d_A2
         "hello"   "hi"

output: p7d_A1    p7d_A2     p7d_A3 
         "hello"    "hi"       "NT"