我正在用 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();
[...]
}
您能给我关于实施它们的正确方法的好建议吗?
此致。
我认为你正在寻找的线路是
(ent->*(spawn->ptr))();
我们来剖析一下。首先,我们需要获取实际的成员函数指针,即
spawn->ptr
因为,在这里,spawn
是一个指针,我们必须使用->
选择ptr
field.
一旦我们有了这个,我们需要使用指向成员选择运算符来告诉ent
选择适当的成员函数:
ent->*(spawn->ptr)
最后,要调用该函数,我们需要告诉 C++ 调用该成员函数。由于 C++ 中的运算符优先级问题,您首先必须将计算结果为成员函数的整个表达式括起来,因此我们有
(ent->*(spawn->ptr))();
无论如何,这是我一段时间以来见过的最奇怪的 C++ 代码行之一。 :-)
在一个完全不相关的注释中,因为您使用的是 C++,所以我会避免使用typedef struct
。说啊
struct t_dEntitySpawn {
std::string name;
void (dEntity::*ptr)();
};
希望这可以帮助!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)