小编And*_*ida的帖子

c ++ - 将基类指针转换为派生类指针

#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;
}
Run Code Online (Sandbox Code Playgroud)

我现在有一些多态性问题,上面的代码总结了一切.我创建了一个Base类指针,并在其中放置了一个新的派生模板类的指针.然后我为派生模板类创建了一个新指针,我希望它具有基类指针指向的引用.即使Base指针(b)指向Derived,也不能将引用传递给Derived类指针(d),因为there's no known conversion from Base * to Derived<int> *(正如编译器所说).

那么有没有一种技巧或另一种方法可以做到这一点?提前致谢.

c++ polymorphism pointers

22
推荐指数
3
解决办法
5万
查看次数

标签 统计

c++ ×1

pointers ×1

polymorphism ×1