c – 如何将成员函数传递给函数指针?

class Child;
class Parent
{
public:
  void (*funcPointer)();
  void (*funcPointer2)(Parent* _this);
  void (Child::*funcPointer3)();
};

class Child: public Parent
{
public:
  void TestFunc(){

  }
  void Do(){
    Parent p;
    p.funcPointer=TestFunc; // error,'=': cannot convert from 'void (__thiscall Child::* )(void)' to 'void (__cdecl *)(void)'
    p.funcPointer2=TestFunc; // error too,'=': cannot convert from 'void (__thiscall Child::* )(void)' to 'void (__cdecl *)(Parent *)'
    p.funcPointer3=TestFunc; //this works
    p.funcPointer3=&Child::TestFunc; // this works too.
    p.funcPointer3();    // error,term does not evaluate to a function taking 0 arguments
  }
};

我如何将一个成员函数传递给一个函数指针,然后如何调用函数指针?

解决方法

你不行您或者传递一个指向静态方法的指针,或者父级也必须接受一个指向该对象的指针.

你可能想看看boost::bindboost::function

#include <boost/bind.hpp>
#include <boost/function.hpp>
struct Y
{
    void say(void) { std::cout << "hallo!";}

    boost::function<void()> getFunc() { return boost::bind(&Y::say,this); }
};

struct X
{
    //non-boost:
    void (Y::*func)();
    Y* objectY;
    void callFunc() { (objectY->*func)(); }

    //boost version:
    boost::function<void()> f;

};


X x;
Y y;
x.f = boost::bind(&Y::say,boost::ref(y));
x.f = y.getFunc();
x.f();
x.func = &Y::say;
x.objectY = &y; 
x.callFunc();

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...