相关疑难解决方法(0)

必须调用对非静态成员函数的引用

我正在使用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成员的指针?

c++ pointers reference

26
推荐指数
2
解决办法
7万
查看次数

如何使用成员函数初始化`std :: function`?

我正在努力学习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)

如何使这项工作,即如何将成员函数作为参数传递?

c++ c++11

2
推荐指数
2
解决办法
6319
查看次数

标签 统计

c++ ×2

c++11 ×1

pointers ×1

reference ×1