基于派生的转换

可以使用 static_cast 将指向基类的指针转换为指向派生类的指针。static_cast 不执行任何运行时检查,并且当指针实际上未指向所需类型时,可能导致未定义的行为。

struct Base {};
struct Derived : Base {};
Derived d;
Base* p1 = &d;
Derived* p2 = p1;                        // error; cast required
Derived* p3 = static_cast<Derived*>(p1); // OK; p2 now points to Derived object
Base b;
Base* p4 = &b;
Derived* p5 = static_cast<Derived*>(p4); // undefined behaviour since p4 does not
                                         // point to a Derived object

同样,可以使用 static_cast 将对基类的引用转换为对派生类的引用。

struct Base {};
struct Derived : Base {};
Derived d;
Base& r1 = d;
Derived& r2 = r1;                        // error; cast required
Derived& r3 = static_cast<Derived&>(r1); // OK; r3 now refers to Derived object

如果源类型是多态的,则 dynamic_cast 可用于执行基于派生的转换。它执行运行时检查,并且可以恢复故障,而不是产生未定义的行为。在指针的情况下,失败时返回空指针。在参考案例中,当 std::bad_cast 类型(或从 std::bad_cast 派生的类)失败时抛出异常。

struct Base { virtual ~Base(); }; // Base is polymorphic
struct Derived : Base {};
Base* b1 = new Derived;
Derived* d1 = dynamic_cast<Derived*>(b1); // OK; d1 points to Derived object
Base* b2 = new Base;
Derived* d2 = dynamic_cast<Derived*>(b2); // d2 is a null pointer