c++ - c++ 中的复杂 dynamic_cast

标签 c++ polymorphism language-lawyer dynamic-cast cross-cast

我在 C++ 中有以下情况:

  • 抽象基类 Abstract1Abstract2。它们是无关的。
  • Foo 派生自 Abstract1Abstract2

我在一个编译单元中,我没有关于类 Foo 的信息(没有声明,没有定义)。只有 Abstract1Abstract2 是已知的。 (实际上,Foo 甚至定义在一个 DLL 中)

dynamic_cast 是否允许从 Abstract1* 转换为 Abstract2*?这是标准吗?

最佳答案

你所描述的是所谓的cross-cast。对于 dynamic_cast<T>(v) , 标准在 [expr.dynamic.cast]/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 [..]

  • 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.

即使没有关于 Foo 的信息,这仍然有效存在于包含类型转换的翻译单元中。

你应该看看 this question也是。

关于c++ - c++ 中的复杂 dynamic_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27042002/

相关文章:

Java参数多态示例

c++ - C++ 纯虚函数调用的性能可变性

c++ - 如何在静态析构函数中安全地使用 `std::error_category`?

c++ - 基类指针可以指向派生类对象。为什么反之不成立?

c++ - 不完整类型的无效使用 'DIR'

c++ - 在使用 vector 和迭代器时与 const 行为作斗争

c++ - 重写类的不同返回值

c - 分配对象和结构的有效类型

c++ - 指向C++寄存器的指针合法吗?

c++ - 如何将pdf文件存储为二进制文件