#include <iostream>
using namespace std;
class Base {
public:
Base() {};
~Base() {};
};
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 = b;
cout << d->raw() << endl;
return 0;
}
我现在有一些多态性的问题,上面的代码总结了所有的内容。我创建了一个Base类指针,并将一个新的派生模板类的指针放入其中。然后我为派生模板类创建了一个新的指针,并希望它引用基类指针所指向的内容。即使Base指针(b)指向Derived,也无法将引用传递给Derived类指针(d),因为编译器说“从Base *到Derived<int> *没有已知的转换”。那么有没有什么技巧或替代方法能够实现呢?谢谢提前。