获取指向对象的成员函数的指针 [英] Get a pointer to object's member function

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

问题描述

这是问题所在:

1)我有一个像这样的班级:

1) I have a class like so:

class some_class
{
public:
    some_type some_value;
    int some_function(double *a, double *b, int c, int d, void *e);
};

2)在some_function内部,我使用some_class对象中的some_values来获得结果.

2) Inside some_function, I use some_values from some_class object to get a result.

3)因此,我有一个具体的对象,我想获得一个指向该对象some_function的指针.

3) So, I have a concrete object and I want to get a pointer to this object some_function.

有可能吗?我不能使用some_fcn_ptr,因为此函数的结果取决于对象的具体some_value.

Is it possible? I can't use some_fcn_ptr because the result of this function depends on the concrete some_value of an object.

如何获取指向对象的some_function的指针?谢谢.

How can I get a pointer to some_function of an object? Thanks.

typedef  int (Some_class::*some_fcn_ptr)(double*, double*, int, int, void*);

推荐答案

您不能,至少它不只是函数的指针.

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

成员函数对于此类的所有实例都是通用的.所有成员函数都具有隐式(第一个)参数this.为了调用特定实例的成员函数,您需要一个指向该成员函数和该实例的指针.

Member functions are common for all instances of this class. All member functions have the implicit (first) parameter, this. In order to call a member function for a specific instance you need a 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 看起来像(C ++ 11提供类似的功能):

Using Boost this can look like (C++11 provides similar functionality):

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

C ++ 11的lambda:

C++11's lambdas:

#include <functional>

Some_class sc;
auto f = [&sc]() { sc.some_function(); };
f();
// or
auto f1 = [](Some_class& sc) { sc.some_function(); };
f1(sc);

这篇关于获取指向对象的成员函数的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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