C++ casting programmatically : can it be done?

后端 未结 8 438
你的背包
你的背包 2021-01-13 06:18

Let\'s say I have a Base class and several Derived classes. Is there any way to cast an object to one of the derived classes without the ne

8条回答
  •  一整个雨季
    2021-01-13 06:36

    Don't.

    Read up on polymorphism. Almost every "dynamic cast" situation is an example of polymorphism struggling to be implemented.

    Whatever decision you're making in the dynamic cast has already been made. Just delegate the real work to the subclasses.

    You left out the most important part of your example. The useful, polymorphic work.

    string typename = typeid(*object).name();
    if(typename == "Derived1") {
       Derived1 *d1 = static_cast< Derived1*>(object);
       d1->doSomethingUseful();
    }
    else if(typename == "Derived2") {
       Derived2 *d2 = static_cast < Derived2*>(object);
       d2->doSomethingUseful();
    }
    ...
    else {
      ...
    }
    

    If every subclass implements doSomethingUseful, this is all much simpler. And polymorphic.

    object->doSomethingUseful();
    

提交回复
热议问题