gpt4 book ai didi

c++ - 使用多重继承进行转换

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:25:56 27 4
gpt4 key购买 nike

如果您有一个 void* 指针指向继承自 BaseABaseB 的派生类,编译器如何转换 void*指向 BaseA*(或 BaseB*)的指针而不知道 void* 指针是 Derived 类型?

最佳答案

事实并非如此。使用 static_castvoid* 进行转换时的唯一保证是:

A value of type pointer to object converted to "pointer to cv void" and back to the original pointer type will have its original value (C++03 §5.2.9/10).

例如,下面的代码是不正确的,因为void*被强制转换为原始指针类型以外的类型(强制转换顺序为B1* -> void* -> B2*):

struct B1 { int i; };
struct B2 { int j; };

struct D : B1, B2 { };

D x;
B1* b1ptr = &x;
void* voidptr = b1ptr;
B2* b2ptr = static_cast<B2*>(voidptr);

尝试在此处使用 b2ptr 会导致未定义的行为。您可以安全地将 voidptr 转换为的唯一类型是 B1*,因为这是从中获得 void* 的类型(好吧,或 char*,因为任何东西都可以通过 char* 访问)。

关于c++ - 使用多重继承进行转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3327631/

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