error: cannot dynamic_cast ‘b’ (of type ‘class Base*’) to type ‘class Derived<int>*’ (source type is not polymorphic)

清泛原创

在将父类型转换为子类型时,可以使用static_cast和dynamic_cast.如果使用dynamic_cast,它要求父类必须为多态的,即要求至少有一个虚函数,因此需要仔细检查类定义中有无虚函数,例如可以将析构函数设置为虚函数.

更正后的代码为(来自: c++ - converting a base class pointer to a derived class pointer)

#include <iostream>
using namespace std;

class Base {
public:
  Base() {};
 virtual  ~Base() {}; // make it polymorphic
};

template<class T>
class Derived: public Base {
  T _val;
public:
  Derived() {}
  Derived(T val): _val(val) {}
  T raw() {return _val;}
};

int main()
{
  Base * b = new Derived<int>(1);
  Derived<int> * d = dynamic_cast<Derived<int>* >(b);
  cout << d->raw() << endl;
  return 0;
}

dynamic_cast

分享到:
评论加载中,请稍后...
创APP如搭积木 - 创意无限,梦想即时!
回到顶部