C++ casting programmatically : can it be done?

后端 未结 8 519
你的背包
你的背包 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:46

    You can do this using dynamic_cast, e.g:

    if ( Derived1* d1 = dynamic_cast(object) ) {
        // object points to a Derived1
        d1->foo();
    }
    else if ( Derived2* d2 = dynamic_cast(object) ) {
        // object points to a Derived2
        d2->bar();
    }
    else {
        // etc.
    }
    

    But as others have said, code such as this can indicate a bad design, and you should generally use virtual functions to implement polymorphic behaviour.

提交回复
热议问题