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

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

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

template
class Derived: public Base {
  T _val;
public         


        
3条回答
  •  时光取名叫无心
    2021-01-31 09:52

    You must change the base type to be polymorphic:

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

    To cast from some supertype to some derived type, you should use dynamic_cast:

    Base *b = new Derived(1);
    Derived *d = dynamic_cast *>(b);
    

    Using dynamic_cast here checks that the typecast is possible. If there is no need to do that check (because the cast cannot fail), you can also use static_cast:

    Base *b = new Derived(1);
    Derived *d = static_cast *>(b);
    

提交回复
热议问题