如何通过指针调用成员函数

How to call a memberfunction by pointer

目前我正在尝试实现一个小的 State-Action-Matrix。 我得到了一个 table,其中包含有关我当前状态的信息,程序将从该状态过渡到新的跟随状态。

在从一种状态转换到另一种状态的过程中,程序应该调用特定的成员函数。

转换示例table:

typedef struct
{
    int state;
    int followState;
    /* POINTER TO MEMBERFUNCTION */
}STATE_TRANSITION;


STATE_TRANSITION stateTransition[] =
{
    { state1, state2, /* ... */ },
    /* ... */
};

要从此 Table 调用的 Memeber 函数位于 class。

class A
{
public:
    int foo(int);
};

我现在的问题是,如何调用 Memeber 函数 'foo' 的示例并将参数传递给它?

如有任何帮助,将不胜感激。

实现查找的类型定义table,从一个当前状态指向后续状态。第一个 typedef 定义了一个成员函数指针。所述指针然后在结构中实现以符号化 Lookuptable.

typedef bool(MP_Commands::*Member)();

typedef struct
{
    uint8_t currState;      // Current State
    uint8_t followState;    // Follow State
    Member  func;           // Transition Function
}STATE_TRANSITION;

然后我将所述 lookup-table 集成为我的 class 的私有属性,因此指针可以访问私有成员函数。

class A
{
private:
    STATE_TRANSITION stateTransitions[15];
    /*...*/
};

Lookup-Table本身实现如下:

static const STATE_TRANSITION _stateTransitions[] =
{ 
    { state1, state2, &A::memberFun },
    /*...*/
};

memcpy(stateTransitions, _stateTransitions,
    LENGTH(stateTransitions) * sizeof(stateTransitions[0]));

---编辑--- 对不起,我忘了提到如何使用这样的实现:

(*this.*stateTransitions[i].transition)();

示例:

if((*this.*stateTransitions[i].transition)())
{ /* Do ... */ }