gpt4 book ai didi

c++ - 在 C++ 中使用不正确的向下转换访问基类成员

转载 作者:太空狗 更新时间:2023-10-29 23:35:09 25 4
gpt4 key购买 nike

下面的 C++ 代码是否正确?

struct Base { int x; };
struct Derived : Base { int y; }
Base * b = new Base;
Derived * d = static_cast<Derived *>(b);
//below we access only d->x, but not d->y
std::cout << d->x;

如果不是,那到底是哪里出了问题? C++ 标准对此有何评论?至少我还没有看到它崩溃过。

最佳答案

这在 [expr.static.cast]/11 中相当简单(强调我的):

A prvalue of type “pointer to cv1 B”, where B is a class type, can be converted to a prvalue of type “pointer to cv2 D”, where D is a class derived from B, if cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. If B is a virtual base class of D or a base class of a virtual base class of D, or if no valid standard conversion from “pointer to D” to “pointer to B” exists ([conv.ptr]), the program is ill-formed. The null pointer value is converted to the null pointer value of the destination type. If the prvalue of type “pointer to cv1 B” points to a B that is actually a subobject of an object of type D, the resulting pointer points to the enclosing object of type D. Otherwise, the behavior is undefined.

您没有 Derived 的子对象,因此这是未定义的行为。


请注意,左值或 xvalue 指针没有特殊情况,并且/8 提到操作数经历了左值到右值的转换。

关于c++ - 在 C++ 中使用不正确的向下转换访问基类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46205151/

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