在C ++中的instanceof等价物 [英] instanceof equivalent in C++
问题描述
我正在用C ++创建一个二维游戏,它使用由瓷砖制成的等级。世界级有一个 add(WorldObject * o)
函数,它既可以接受磁贴,也可以接受敌人等实体。 Tile
和实体
类都派生自 WorldObject
。在每种情况下,都应将对象添加到实体
列表中;但如果它是一个图块,它也应该被添加到 tiles
列表中。
I'm creating a 2D game in C++ that uses levels made out of tiles. The world class has an add(WorldObject* o)
function that can both accept a tile or an entity such as an enemy. Both the Tile
and the Entity
class are derived from WorldObject
. In every case, the object should be added to the entities
list; but if it is a tile, it should also be added to the tiles
list.
World.h
class World {
private:
list<WorldObject*> content;
list<Tile*> tiles;
public:
void add(WorldObject*);
}
World.cpp
World.cpp
void World::add(WorldObject* o) {
content.push_back(o);
if(*o instanceof Tile) //What do I need to put here?
tiles.push_back(o);
}
如何检查对象在C ++中是否具有特定类型?这与类型转换和虚函数以及类似的东西无关,因为我不想在此时调用对象的函数;如果它有某种类型,我只需要将它添加到一个单独的列表中。
在Java中,我可以执行 if(instance instanceof Class)
。如何在C ++中执行此操作?
How do I check whether an object has a specific type in C++? It's nothing about typecasting and virtual functions and things like that because I don't want to invoke functions to the object at this time; I just need to add it to a separate list if it has a certain type.
In Java, I can do if(instance instanceof Class)
. How can I do this in C++?
推荐答案
dynamic_cast
将检查看你是否可以将 o
转发给 Tile
。如果可以,它将返回有效的 Tile *
,否则它将返回null Tile *
:
A dynamic_cast
will check to see if you can downcast o
to Tile
. If you can, it will return a valid Tile*
, else it will return a null Tile*
:
void World::add(WorldObject* o) {
content.push_back(o);
if (Tile* t = dynamic_cast<Tile*>(o)) {
tiles.push_back(t);
}
}
这篇关于在C ++中的instanceof等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!