C++ Function pointer to member function of a static pointer object

I have a class (B) which has a static member pointer to an object of another class (A). In one member function of the first class (B), I need a function pointer that points to a member function of the second class (A).

class A
{
public:
    int DoubleValue(int nValue)
    {
        return nValue * 2;
    }
};

class B
{
private:
    static A* s_pcA;
public:
    void Something()
    {
        // Here a need the function pointer to s_pcA->DoubleValue()
    }
};

I have tried this:

int (*fpDoubleValue) (int nValue) = s_pcA->DoubleValue;

But Xcode says "Reference to non-static member function must be called".


You cannot obtain pointer to a member function of a class instance. Instead, you need to create a function object that contains pointer to a class instance and to a member function. You can use std::bind for that purpose:

auto fpDoubleValue = std::bind (&A::DoubleValue, s_pcA , std::placeholders::_1);

Lambda函数也可以使用:

auto fpDoubleValue = [](int nValue) { return s_pcA->DoubleValue(nValue); };

You may use a pointer on method:

int (A::*fpDoubleValue) (int nValue) = &A::DoubleValue;

or in your case make the method static since it doesn't depend of this :

class A
{
public:
    static int DoubleValue(int nValue) { return nValue * 2; }
};

then

int (*fpDoubleValue) (int nValue) = &A::DoubleValue;
链接地址: http://www.djcxy.com/p/96358.html

上一篇: 类成员和成员函数的内存位置

下一篇: C ++函数指向静态指针对象的成员函数的指针