gpt4 book ai didi

c++ - 失败和错误的类型转换

转载 作者:太空宇宙 更新时间:2023-11-04 16:13:50 25 4
gpt4 key购买 nike

您能否解释一下 ill-formed castfailed cast 之间的区别。例如:

class A { virtual void f(); };
class B { virtual void g(); };
class D : public virtual A, private B { };

void g() {
D d;
B* bp = (B*)&d; // cast needed to break protection
A* ap = &d; // public derivation, no cast needed
D& dr = dynamic_cast<D&>(*bp); // fails
ap = dynamic_cast<A*>(bp); // fails
bp = dynamic_cast<B*>(ap); // fails
ap = dynamic_cast<A*>(&d); // succeeds
bp = dynamic_cast<B*>(&d); // ill-formed (not a run-time check)
}

最佳答案

不管名称如何,当您使用 dynamic_cast 时要进行向上转换(派生->基础),转换是在编译时完成的,其行为方式与 static_cast 相同或隐式转换 - 如果基数不明确或不可访问,则程序格式错误,这意味着编译器必须产生诊断。 §5.2.7 [expr.dynamic.cast]/p5:

[For the expression dynamic_cast<T>(v):]

If T is "pointer to cv1 B" and v has type "pointer to cv2 D" such that B is a base class of D, the result is a pointer to the unique B subobject of the D object pointed to by v. Similarly, if T is "reference to cv1 B" and v has type cv2 D such that B is a base class of D, the result is the unique B subobject of the D object referred to by v. 67 The result is an lvalue if T is an lvalue reference, or an xvalue if T is an rvalue reference. In both the pointer and reference cases, the program is ill-formed if cv2 has greater cv-qualification than cv1 or if B is an inaccessible or ambiguous base class of D.

67 The most derived object (1.8) pointed or referred to by v can contain other B objects as base classes, but these are ignored.

在其他情况下(向下或向侧面 throw ),检查在运行时执行。如果失败,则转换结果是指针转换的空指针,以及 std::bad_cast。引用转换的异常。

关于c++ - 失败和错误的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25102816/

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