我正在使用C++(而不是C++ 11).我需要在类中创建一个指向函数的指针.我尝试做以下事情:
void MyClass::buttonClickedEvent( int buttonId ) {
// I need to have an access to all members of MyClass's class
}
void MyClass::setEvent() {
void ( *func ) ( int );
func = buttonClickedEvent; // <-- Reference to non static member function must be called
}
setEvent();
Run Code Online (Sandbox Code Playgroud)
但是有一个错误:"必须调用非静态成员函数的引用".如何制作指向MyClass成员的指针?
我正在努力学习std::function,这是我的代码:
#include <iostream>
#include <functional>
struct Foo {
void print_add(int i){
std::cout << i << '\n';
}
};
typedef std::function<void(int)> fp;
void test(fp my_func)
{
my_func(5);
}
int main(){
Foo foo;
test(foo.print_add);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器错误:
error: cannot convert 'Foo::print_add' from type 'void (Foo::)(int)' to type 'fp {aka std::function<void(int)>}'
test(foo.print_add);
Run Code Online (Sandbox Code Playgroud)
如何使这项工作,即如何将成员函数作为参数传递?