gpt4 book ai didi

c++ - dynamic_cast<> 是否仅限于沿继承层次结构的直接转换?

转载 作者:太空狗 更新时间:2023-10-29 19:58:36 26 4
gpt4 key购买 nike

代码

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?

请注意,为了使代码简单,我省略了虚拟细节。

如果 dynamic_cast<> 仅限于沿继承层次结构的直接转换,那么我希望上面的代码在运行时失败(因为 B& 与 A& 无关)。

但是,如果它更通用/更灵活,代码应该可以工作,因为所引用对象的真实类型是 C 类型(并且 C 可以被称为 B& 或 A&)。

C++ 规范对这种情况有何看法?

最佳答案

dynamic_cast<T>(v)可能会下降到最派生的对象,其中 v是一个子对象,然后向上(可能是不同的分支)找到一个明确的基类 T是指针或引用。来自标准:

5.2.7/8 If C is the class type to which T points or refers, the run-time check logically executes as follows:

  • If, in the most derived object pointed (referred) to by v, v points (refers) to a public base class subobject of a C object, and if only one object of type C is derived from the subobject pointed (referred) to by v the result points (refers) to that C object.
  • Otherwise, if v points (refers) to a public base class subobject of the most derived object, and the type of the most derived object has a base class, of type C, that is unambiguous and public, the result points (refers) to the C subobject of the most derived object.
  • Otherwise, the run-time check fails.

关于c++ - dynamic_cast<> 是否仅限于沿继承层次结构的直接转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20015309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com