如果您有一个 void* 指针指向继承自 BaseA
和 BaseB
的派生类,编译器如何转换 void*
指向 BaseA*
(或 BaseB*
)的指针而不知道 void*
指针是 Derived
类型?
最佳答案
事实并非如此。使用 static_cast
与 void*
进行转换时的唯一保证是:
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/