c++ - converting a base class pointer to a derived class pointer

前端 未结 3 2018
误落风尘
误落风尘 2021-01-31 09:02
#include 
using namespace std;

class Base {
public:
  Base() {};
  ~Base() {};
};

template
class Derived: public Base {
  T _val;
public         


        
3条回答
  •  萌比男神i
    2021-01-31 10:03

    You can use dynamic_cast

    Derived * d = dynamic_cast *>(b);
    

    If the cast fails (the base pointer does not point to the requested derived type), it returns null.

    However, for dynamic_cast to work, your base class must have at least one virtual function. I suggest you make the destructor virtual (this is also prevents other potential problems deleting your objects).

    Use of dynamic_cast may indicate bad design in your code.

    Note that if you are 100% sure the base pointer, points to your derived type, then you may replace it with static_cast, which is slightly faster. Personally I prefer the extra safety check in general.

提交回复
热议问题