gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:20:50 26 4
gpt4 key购买 nike

我们有 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-timecheck is performed:

a) The most derived object pointed/identified by expression isexamined. If, in that object, expression points/refers to a publicbase of Derived, and if only one object of Derived type is derivedfrom the subobject pointed/identified by expression, then the resultof 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/

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