如何将成员函数传递给函数指针? [英] How Can I Pass a Member Function to a Function Pointer?

查看:33
本文介绍了如何将成员函数传递给函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

How can I pass a member function to a function pointer, and then how would I then call that function pointer?

推荐答案

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

You can't. You either pass a pointer to a static method or Parent has to accept also a pointer to the object.

您可能想查看 boost::bindboost::function:

You might want to look at boost::bind and boost::function for that:

#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();

这篇关于如何将成员函数传递给函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆