gpt4 book ai didi

c++ - 向下转换非多态类型?

转载 作者:行者123 更新时间:2023-12-04 01:06:14 24 4
gpt4 key购买 nike

请考虑以下 C++20 程序:

struct B { B(); private: int whatever; }; // non-aggregate
struct D : B { D(); int x; private: int whatever2; }; // non-aggregate

int main() {
D* d = new D;
d->x = 42;
B* b = (B*) d;
D* d2 = (D*) b;
return d2->x;
}

这个程序是否格式错误或有未定义的行为?

也就是说,是否允许将指向非多态类型的派生对象的基子对象的指针转换为指向派生对象本身的指针?

如果是这样,*_cast<T> 中的一个会吗?函数比 C 风格的转换更合适?

(此外,如果指针指向的 B 对象不是 D 类型对象的基础子对象,那么它的行为是未定义的,对吗?实现无法检查转换是否是正确,就像 dynamic_cast 一样?)

最佳答案

Is this program ill-formed or have undefined behaviour?

这个程序结构良好。您可以毫无问题地将指针从基类型转换为子类型。

If so, would one of the *_cast functions be more appropriate than the C-style cast?

当然!使用的默认转换为 static_cast<T>(...) .它将避免从/向不相关的类型进行强制转换,这会导致未定义的行为。

例如,C 风格的转换将接受您的代码 even if B and D are unrelated , 但是 refuses the code using static_cast

关于c++ - 向下转换非多态类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66344389/

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