1

按下按钮时我需要调用一个函数。以下函数应接受要调用的函数:

void ButtonLayer::LoadButton(void(*func)()) {
     // do button loading stuff
     // if button is clicked...
     func();
}

除了在单独的命名空间中传递函数会产生以下错误之外,这将起作用:

argument of type "void(OtherLayer::*)()" is incompatiable with parameter of type "void(*)()"

我不想让我传递的每个函数都是静态的以避免这个问题,所以我需要某种方法将命名空间中的函数转换为 void(*) 类型。我尝试过静态转换,但我不确定确切的语法,因为我是 C++ 新手

4

2 回答 2

0

看来你想传递一个成员函数。

这个例子可以帮助你。

class A {
public:
    int i;
    int fun(int j) {
        return i + j;
    };
};
void fun(int j, A ob, int (A::* p)(int)) {
    std::cout << (ob.*p)(j);
}
void main() {
    int (A:: * fp)(int);    //declare fp as a function pointer in class A
    fp = &A::fun;          //init fp
    A obj;
    obj.i = 1;
    fun(123, obj, fp);
}
于 2020-04-07T08:21:55.877 回答
0

基于@Yksisarvinen 和@MSalters 评论,解决方案是:

void ButtonLayer::LoadButton(std::function<void()>) {
     // do button loading stuff
     // if button is clicked...
     func();
}

然后调用它:

LoadButton([this] { functionToCall; });
于 2020-04-07T08:37:16.843 回答