是dynamic_cast<>限制在继承层次结构中的直接转换? [英] Is a dynamic_cast<> limited to direct casts along the inheritance hierarchy?
问题描述
CODE
struct A { }; // virtual details there, but left out
struct B { }; // virtual details there, but left out
struct C : A, B { }; // virtual details there, but left out
C 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.
如果dynamic_cast<>限于沿着继承层次结构的直接转换,那么我期望上述代码在运行时失败(因为B&与A&不相关)。
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&).
然而,如果它更通用/灵活,代码应该工作,因为被引用对象的真实类型是C类型(和C可以被称为B&或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&).
C ++规范对这种情况有什么看法?
推荐答案
现在,代码不会编译,因为没有任何类有任何虚函数 - 需要使用 dynamic_cast
。如果你添加至少一个虚函数(例如,虚拟dtor到 B
,那么是的,因为 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();
}
输出(使用VC ++和g ++,这不是最前沿的,所以除了一个真正的古老的编译器,我希望它是正确的):
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:
A
C
显示 a
的静态类型为 A
,但动态类型为 C
。
Showing that the a
has a static type of A
, but a dynamic type of C
.
这篇关于是dynamic_cast<>限制在继承层次结构中的直接转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!