継承の裏ワザ

inheritance-technique.png

ある特定の子供だけ違う挙動にしたい

javaではinstanceofが有効

void func(Kerdashian k){
   if(k instanceof Khloe){//カーダシアン家の中でもクロエだけに特別な処理をしたい場合
      doSomethingSpecial();
}
}

C++の場合は簡単にはいかない

http://stackoverflow.com/questions/500493/c-equivalent-of-instanceof

NewType* v = dynamic_cast<NewType*>(old);
if(v != 0) {
   // old was safely casted to NewType
   v->doSomething();
}
if(old->getType() == BOX) {
   Box* box = static_cast<Box*>(old);
   // Do something box specific
}
// Here we have a SpecialBox class that inherits Box, since it has its own type
// we must check for both BOX or SPECIAL_BOX
if(old->getType() == BOX || old->getType() == SPECIAL_BOX) {
   Box* box = static_cast<Box*>(old);
   // Do something box specific
}

inheritance reverse-engineering

サポートサイト Wikidot.com inheritancereverse-engineering