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

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

问题描述

这里是问题:
1.)我有一个类

Here is the problem: 1.) i have a class

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的指针。
是可能吗?我不能使用some_fcn_ptr,因为这个函数的结果取决于具体some_value的对象。如何获得一个指向some_function的对象的指针?感谢。

3.) So i have a concrete object and i want to get a pointer to this object some_function. Is it possible? I cant use some_fcn_ptr, because result of this function depends on concrete some_value of a object. 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 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);

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

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