我正在用 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();
[...]
}
你能给我一个关于实施它们的正确方法的好建议吗?
最好的祝福。