C++ C++;将动态方法指针作为不同类的方法参数传递

C++ C++;将动态方法指针作为不同类的方法参数传递,c++,class,oop,function-pointers,C++,Class,Oop,Function Pointers,我正在制作一个allegro游戏,其中button类应该是独立的,所以我将函数指针放在OnClick事件的button对象内部。在整个项目中,我一直在将全局函数放在MyButton构造函数的参数中,一切都正常工作—当我尝试在其中传递Node::OnClick()时出现了问题: 节点h: class Node { private: static int _id; int id; bool active; std::vector<Node*> neighb

我正在制作一个allegro游戏,其中button类应该是独立的,所以我将函数指针放在OnClick事件的button对象内部。在整个项目中,我一直在将全局函数放在MyButton构造函数的参数中,一切都正常工作—当我尝试在其中传递Node::OnClick()时出现了问题:

节点h:

class Node {
private:
    static int _id;
    int id;
    bool active;
    std::vector<Node*> neighbours;
    std::vector<bool> mask;
public:
    Node();
    int getId();
    void addNeighbour(Node* neighbour);
    void OnClick();
    void Check();
    void Uncheck();
    bool isActive();
};
主要内容:

错误:

error C3867: 'Node::OnClick': function call missing argument list; use '&Node::OnClick' to create a pointer to member
这段代码执行得很好:

buttons[i] = new MyButton(scarab1, button_coords[0]-27, button_coords[1]-27, &testOnClick);
一旦我将&Node::OnClick放入ctor参数,如下所示:

buttons[i] = new MyButton(scarab1, button_coords[0]-27, button_coords[1]-27, &Node::OnClick);
然后我得到:

main.cpp(135): error C2664: 'MyButton::MyButton(ALLEGRO_BITMAP *,int,int,void (__cdecl *)(void))' : cannot convert parameter 4 from 'void (__thiscall Node::* )(void)' to 'void (__cdecl *)(void)'

您的
节点::OnClick
函数的类型为
void(节点::*)(void)

您可能需要考虑使用。(或取决于您可用的内容。
mem\u-fun
已被弃用,并已被
mem\u-fn
取代)

memfn(&Node::OnClick)
在这种情况下将返回类型为
void(*)(void)
的函数指针。(技术上未指定类型。)

见鬼,在这一点上,我建议把函数指针忘在一起,然后仔细研究一下


好的,
std::function
替代方案在这里会更干净:

// Pass *current here
auto fn = std::bind(&Node::OnClick, class_instance);

上面的行将从绑定到类实例的成员函数中返回一个可调用对象。将其传递给函数,但不要使用函数指针,而是使用
std::function

您可能还想查看一下。它已经为您实现了所有信号/插槽处理。如何将对象合并到该指针中?Node::OnClick似乎是静态的,
mem\u fn(&Node::OnClick,*current)1>main.cpp(136):错误C2780:'std::tr1::_Call_wrapper std::tr1::mem_fn(_Rx _Arg0::*const)':需要1个参数-2个提供的参数-1>D:\VisualStudio\VC\include\functional(28):请参阅“std::tr1::mem\u fn”的声明它似乎不需要2个参数,那么对象的std::function方式呢,更干净的解决方案。只有在分析应用程序并发现瓶颈是调用存储的std::Function对象时,才真正需要函数指针。std::函数使用更干净。
main.cpp(135): error C2664: 'MyButton::MyButton(ALLEGRO_BITMAP *,int,int,void (__cdecl *)(void))' : cannot convert parameter 4 from 'void (__thiscall Node::* )(void)' to 'void (__cdecl *)(void)'
// Pass *current here
auto fn = std::bind(&Node::OnClick, class_instance);