我在 C++ 中有以下情况:
- 抽象基类
Abstract1
和Abstract2
。它们是无关的。 - 类
Foo
派生自Abstract1
和Abstract2
我在一个编译单元中,我没有关于类 Foo
的信息(没有声明,没有定义)。只有 Abstract1
和 Abstract2
是已知的。
(实际上,Foo 甚至定义在一个 DLL 中)
dynamic_cast 是否允许从 Abstract1*
转换为 Abstract2*
?这是标准吗?
最佳答案
你所描述的是所谓的cross-cast。对于 dynamic_cast<T>(v)
, 标准在 [expr.dynamic.cast]/8
If
C
is the class type to whichT
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 aC
object [..]Otherwise, if
v
points (refers) to apublic
base class subobject of the most derived object, and the type of the most derived object has a base class, of typeC
, that is unambiguous andpublic
, the result points (refers) to theC
subobject of the most derived object.
即使没有关于 Foo
的信息,这仍然有效存在于包含类型转换的翻译单元中。
你应该看看 this question也是。
关于c++ - c++ 中的复杂 dynamic_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27042002/