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;
}
上一篇:passing xxx as 'this' argument of xxx discards qualifiers
下一篇:/usr/include/c++/4.9/bits/stl_iterator_base_types.h:165:53: error: ‘int’ is not a class, struct, or union type