且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-15 15:11:30

您必须将基本类型更改为多态:

You must change the base type to be polymorphic:

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

要从某个超类型转换为某个派生类型,您应该使用 dynamic_cast

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

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

使用 dynamic_cast 可能。如果没有必要进行检查(因为转换不会失败),你还可以使用 static_cast

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<int>(1);
Derived<int> *d = static_cast<Derived<int> *>(b);