C++成员函数指针

Axe*_*ard 3 c++ pointers class pointer-to-member

我正在用C++做一个小游戏,我发现了类成员函数指针.我不知道让它们以正确的方式工作,但这是我的尝试.

// A struct where the function pointer will be stored for the call
// By the way, is there a way to do the same thing with classes ?
// or are structs still fine in C++ ? (Feels like using char instead of string)
typedef struct      s_dEntitySpawn
{
  std::string       name;
  void          (dEntity::*ptr)();
} t_dEntitySpawn;

// Filling the struct, if the entity's classname is "actor_basicnpc",
// then I would like to do a call like ent->spawnBasicNPC
t_dEntitySpawn      dEntitySpawns[] = {
  { "actor_basicnpc", &dEntity::spawnBasicNPC },
  { 0, 0 }
};

// This is where each entity is analyzed
// and where I call the function pointer
void            dEntitiesManager::spawnEntities()
{
  dEntity       *ent;
  t_dEntitySpawn    *spawn;

    [...]

      // It makes an error here, feels very weird for me
      if (!spawn->name.compare(ent->getClassname()))
        ent->*spawn.ptr();

    [...]
}
Run Code Online (Sandbox Code Playgroud)

你能否就正确实施方法给我一个很好的建议?

最好的祝福.

tem*_*def 5

我认为你正在寻找的那条线是

(ent->*(spawn->ptr))();
Run Code Online (Sandbox Code Playgroud)

让我们剖析一下.首先,我们需要获取实际的成员函数指针,即

spawn->ptr
Run Code Online (Sandbox Code Playgroud)

因为,这里spawn是一个指针,我们必须使用它->来选择ptr字段.

一旦我们有了这个,我们需要使用指向成员选择的指针运算符告诉ent选择适当的成员函数:

ent->*(spawn->ptr)
Run Code Online (Sandbox Code Playgroud)

最后,要调用该函数,我们需要告诉C++调用这个成员函数.由于C++中的运算符优先级问题,您首先必须将整数表达式括起来,该表达式求值为成员函数,因此我们有

(ent->*(spawn->ptr))();
Run Code Online (Sandbox Code Playgroud)

对于它的价值,这是我在一段时间内看到的最奇怪的C++代码行之一.:-)

在一个完全不相关的注释,因为你正在使用C++,我会避免使用typedef struct.说啊

struct t_dEntitySpawn {
  std::string name;
  void (dEntity::*ptr)();
};
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!