c++ - 动态转换规范(规则)说明

标签 c++ casting dynamic-cast

我们有 dynamic_cast 的一般形式:

dynamic_cast < new-type > ( expression )


我对这条规则 (5a) 的粗体部分特别困惑:

5: If expression is a pointer or reference to a polymorphic type Base, and new-type is a pointer or reference to the type Derived a run-time check is performed:

a) The most derived object pointed/identified by expression is examined. If, in that object, expression points/refers to a public base of Derived, and if only one object of Derived type is derived from the subobject pointed/identified by expression, then the result of the cast points/refers to that Derived object. (This is known as a "downcast".)


你能举一个例子,这部分不满足吗?
以上摘录来自 cppreference:cppreferenc

最佳答案

充实多继承示例@Peter 总结:

     Base1
     /   \  <-- Virtual inheritance here
  Base2  Base2
    |     | <-- Nonvirtual inheritance here and below
  Left   Right
    \     /
    Derived

Base1* p_base1 = new Derived();
Base2* p_base2 = dynamic_cast<Base2*>(p_base1); // Which Base2?
有两种不同的Base2 Derived 中的对象对象,那么应该是哪个 p_base2指向?
代码示例:
#include <iostream>

struct Base1 { virtual ~Base1() = default; };
struct Base2 : virtual Base1 { };
struct Left : Base2 { };
struct Right : Base2 { };
struct Derived : Left, Right {
    Derived() : Base1() {}
};

int main()
{
    Base1* p_base1 = new Derived();
    Base2* p_base2 = dynamic_cast<Base2*>(p_base1);
    std::cout << std::boolalpha;
    std::cout << "p_base1 == nullptr: " << (p_base1 == nullptr) << '\n';
    std::cout << "p_base2 == nullptr: " << (p_base2 == nullptr);
    delete p_base1;
}
在这里要小心一点:Base1几乎是继承的,所以只有一个 Base1子对象,我们实际上可以初始化 p_base1 .然而,Derived非虚拟地继承自 LeftRight ,这意味着它有两个 Base2 的实例.因此,向下转型失败。
输出:
p_base1 == nullptr: false
p_base2 == nullptr: true

关于c++ - 动态转换规范(规则)说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67006646/

相关文章:

java - 将子类转换为父类(super class)实现的子接口(interface)

c# - 使用接口(interface)的隐式运算符

c++ - dynamic_cast 返回 std::bad_cast 我不知道为什么

c++ - 从 Julia 调用具有 std::vectors 作为输入和输出参数的 C++ 函数

c++ - #if 0 后面到底可以放什么?

casting - 将 Vec<u32> 就地转换为 Vec<u8> 且开销最小

c++ - 在实践中,从父级到子级的 dynamic_cast 何时有用?这总是不好的做法吗?

c++ - 无法将 void* 动态转换为模板类

c++ - 函数名称作为参数但具有不同数量的参数

c++ - 类赋值运算符=问题