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

标签 c++ methods function-pointers pointer-to-member delayed-execution

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
  }
};

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

最佳答案

你不能。您要么传递一个指向静态方法的指针,要么 Parent 也必须接受一个指向该对象的指针。

您可能想看看 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++ - 如何将成员函数传递给函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4296281/

相关文章:

c++ - C++ 中的继承有多昂贵或多昂贵

c++ - 如何在字符串中获取 0 到 1700 之间的随机数?

c++ - 对 bool 函数指针的参数感到困惑

c++ - 指向模板函数的函数指针

c++ - 函数模板实例的地址可以作为函数指针传递给某个函数吗?

c++ - 如何返回对 'empty' 对象的引用

java - 如何编写java方法(如果String x = to String y返回String z)

java - 将方法调用放入 ArrayList?

c# - 类方法可以为类的每个实例使用不同的代码吗?

c++ - 什么终止将输入读入 int