dynamic_cast的cross cast问题

最近面试被问了一个问题,也就是dynamic_cast的能否侧向转换:

#include <iostream>

class Base {
public:
    virtual void baseMethod() {}
};

class Base1 {
public:
    virtual void base1Method() {}
};

class Derived : public Base1, public Base {
public:
    void derivedMethod() {}
};

int main() {
    Derived* derivedPtr = new Derived();

    Base* basePtr = dynamic_cast<Base*>(derivedPtr);
    if (basePtr) {
        // 从 Base 指针再转换到 Base1
        Base1* base1Ptr = dynamic_cast<Base1*>(basePtr);
        if (base1Ptr) {
            std::cout << "Conversion successful" << std::endl;
        } else {
            std::cout << "Second conversion failed" << std::endl;
        }
    } else {
        std::cout << "First conversion failed" << std::endl;
    }

    delete derivedPtr;

    return 0;
}

当时我回答是不可以,但事后在本机上实验得到的结果是:Conversion successful

在网上收寻一阵,发现一个06年的文档中:

dynamic_cast Operator 

The dynamic_cast operator can also be used to perform a “cross cast.” Using the same class hierarchy, it is possible to cast a pointer, for example, from the B subobject to the Dsubobject, as long as the complete object is of type E.

发现自己真是个C++菜鸡,寄!

上一篇
下一篇