在这里,钩子函数本身需要检查也属于类层次结构的数据成员的 typeid。因此,我为该类层次结构定义了一个模板方法。这是我遇到的混乱:
void Person::leave() {
// code
hook(); // private virtual
// code
}
void Girl::hook() { // Girl is a derived class of Person, with data member location
// of type Location which itself has a derived class House
// code
location.locationHook(this);// what happens here depends on what kind of location she is in
// code
}
void Location::locationHook(Person* person) {
// Oh oh! This depends on what class person is
}
void House::locationHook(Person* person) {
// Oh oh! This depends on what class person is
}
所以对于这种情况,我不得不求助于我的原始方法,即为每种类型的 Person 派生类使用 typeid(*person) 和 dynamic_cast 和 if 语句来定义虚拟 locationHook,对吗?