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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.