dynamic
dynamic_cast 仅限于继承层次结构的直接转换吗?(Is a dynamic_cast limited to direct casts along the inheritance hierarchy?)码
struct A { }; // virtual details there, but left outstruct B { }; // virtual details there, but left outstruct C : A, B { }; // virtual details there, but left outC c;B& b = c;A& a = dynamic_cast<A&>( b ); // will this cast succeed at run-time?请注意,我忽略了虚拟细节以使代码简单。
如果dynamic_cast <>仅限于继承层次结构的直接转换,那么我预计上面的代码在运行时会失败(因为B&与A&无关)。
但是,如果它更通用/灵活,则代码应该起作用,因为所引用对象的真实类型是C类型的(并且C可以被称为B&或A&)。
C ++规范对这种情况有何看法?
CODE
struct A { }; // virtual details there, but left outstruct B { }; // virtual details there, but left outstruct C : A, B { }; // virtual details there, but left outC c;B& b = c;A& a = dynamic_cast<A&>( b ); // will this cast succeed at run-time?Note that I have left out the virtual details to keep the code simple.
If dynamic_cast<> is limited to direct casts along the inheritance hierarchy, then I expect the code above to fail at run-time (because B& is unrelated to A&).
However, if it is more generic/flexible, the code should work, because the true-type of the referred to object is of C type (and C can be referred to as B& or A&).
What do the C++ specifications say about this case?
最满意答案目前,代码不会编译,因为没有任何类具有任何虚函数 - 要求使用dynamic_cast 。 如果您至少添加一个虚拟功能(例如,将一个虚拟驱动器添加到B ,则是的,因为C是从B公开导出的,所以演员阵容将会成功。
以下是一些快速演示代码:
#include <iostream>struct A { virtual void junk() { std::cout << "A"; } void trash() { std::cout << "A"; } virtual ~A() {}};struct B { virtual ~B(){} void trash() { std::cout << "B"; } void junk() { std::cout << "B"; }};struct C : virtual A, virtual B { void trash() { std::cout << "C"; } void junk() { std::cout << "C"; }}; int main() { C c; B& b = c; A& a = dynamic_cast<A&>(b); a.trash(); std::cout << "\n"; a.junk();}输出结果(包括VC ++和g ++,这不是最前沿的,所以我希望除了一个真正古老的编译器以外的其他东西)是:
AC显示a具有A的静态类型,但是具有C的动态类型。
Right now, the code won't compile because none of the classes has any virtual functions -- a requirement to use dynamic_cast. If you add at least one virtual function (e.g., a virtual dtor to B, then yes, since a C is derived publicly from B, the cast will succeed.
Here's a bit of quick demo code:
#include <iostream>struct A { virtual void junk() { std::cout << "A"; } void trash() { std::cout << "A"; } virtual ~A() {}};struct B { virtual ~B(){} void trash() { std::cout << "B"; } void junk() { std::cout << "B"; }};struct C : virtual A, virtual B { void trash() { std::cout << "C"; } void junk() { std::cout << "C"; }}; int main() { C c; B& b = c; A& a = dynamic_cast<A&>(b); a.trash(); std::cout << "\n"; a.junk();}The output (with both VC++ and g++, and this isn't cutting edge, so I'd expect anything but a truly ancient compiler to get it right) is:
ACShowing that the a has a static type of A, but a dynamic type of C.