且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取指向对象成员函数的指针

更新时间:2023-11-12 23:32:28

你不能,至少它不会指向函数的指针。

You cannot, at least it won't be only a pointer to a function.

成员函数对于此类的所有实例都是常见的。所有成员函数都有隐式(第一个)参数 - this 。要调用特定实例的成员函数,您需要指向此成员函数和此实例的指针。

Member function is common for all instances of this class. All member functions have implicit (first) parameter - this. To call a member function for specific instance you need pointer to this member function and this instance.

class Some_class
{
public:
    void some_function() {}
};

int main()
{
    typedef void (Some_class::*Some_fnc_ptr)();
    Some_fnc_ptr fnc_ptr = &Some_class::some_function;

    Some_class sc;

    (sc.*fnc_ptr)();

    return 0;
}

更多信息请访问 C ++常见问题

使用 Boost 看起来像:

#include <boost/bind.hpp>
#include <boost/function.hpp>

boost::function<void(Some_class*)> fnc_ptr = boost::bind(&Some_class::some_function, _1);
Some_class sc;
fnc_ptr(&sc);