最近面试被问了一个问题,也就是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年的文档中:
发现自己真是个C++菜鸡,寄!