我们有 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
非虚拟地继承自 Left
和 Right
,这意味着它有两个 Base2
的实例.因此,向下转型失败。输出:
p_base1 == nullptr: false
p_base2 == nullptr: true
关于c++ - 动态转换规范(规则)说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67006646/