1

所以我有一个类层次结构,它本质上将Entity类作为父抽象类和一堆从它派生的其他类,例如Door, Player,Ground等。

vector我还有一个存储指向类型对象的指针的三维空间,并用派生对象Entity填充它。vectorDoor类中,我有一个名为的方法isOpen(),它只返回一个bool. 这个函数是特定于Door类的,既不在Entity类中,也不在它的任何其他派生中(因为我不需要检查,例如,一个Ground对象是否打开)。

Door现在,知道在vector位置i,存在一个类型的对象jk我想像这样调用该方法isOpenvector[i][j][k]->isOpen()不幸的是,当我这样做时,编译器返回class Entity has no member named isOpen(). 这是可以理解的,因为该函数isOpen()是该类独有的Door,但是我该怎么做才能使这种调用成为可能?

4

3 回答 3

2

Consider polymorphic casting as supported by the language using dynamic_cast<> For references it will throw an exception (std::bad_cast) but for pointers if the target type is not compatible it will simply return NULL, so... assuming your base class and its derivations are indeed polymorphic (i.e. at least one virtual method):

Door* pDoor = dynamic_cast<Door*>(vector[i][j][k]);
if (pDoor)
    pDoor->isOpen();

Comments about the design withheld. Opinions are like... yeah. everyone has one.

于 2013-08-19T21:23:32.957 回答
2

One way to solve this is with a down cast to a Door * first. However, in order for this down cast to be type safe, you should use dynamic_cast<Door *>(). If Entity does not already have a virtual method, you can add a virtual destructor.

class Entity {
    //...
    virtual ~Entity () {}
};

void foo (Entity *e) {
    //...
    Door *door = dynamic_cast<Door *>(e);
    if (door) {
        if (door->isOpen()) {
            //...
        }
    }
    //...
}
于 2013-08-19T21:24:20.267 回答
2

简短的回答:

将实体扔到一扇门上:static_cast<Door*>(vector[i][j][k])->isOpen()

长答案:

如果您需要知道特定派生类型位于特定位置,则您的设计不合适。解决这个问题可能就像将isOpen()函数移动到 Entity 并返回默认实现一样简单true。或者它可能需要对与vector.

于 2013-08-19T21:08:30.313 回答