且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 void* 到基类指针的转换

更新时间:2021-11-18 00:56:17

void* 只能转换回其原始类型.当您将 Derived* 存储在 void* 中时,您只能转换回 Derived*不能 Base*.

void*'s can only be converted back to their original type. When you store a Derived* in a void*, you can only cast back to Derived*, not Base*.

这在多重继承中尤为明显,因为您的派生对象可能不一定与您的基地址位于同一地址.如果你真的需要用 void* 存储(和检索)东西,总是首先转换为基本类型,这样你就有了一种稳定的方法来取回对象:

This is especially noticeable with multiple inheritance, as your derived object might not necessarily be at the same address as your base. If you really need to store things (and retrieve things) with void*, always cast to the base type first, so you have a stable way of getting the object back:

#include <iostream>

struct base { int type; };
struct intruder { int iminyourclassstealingyourbase; };
struct derived : intruder, base {};

int main()
{
    derived d; d.type = 5;

    void* good = (base*)&d;
    void* bad = &d;

    base* b1 = (base*)good;
    base* b2 = (base*)bad;

    std::cout << "good: " << b1->type << "
";
    std::cout << "bad: " << b2->type << "
";
}

如果您想返回派生类型,请使用 dynamic_cast(或 static_cast,如果您保证它必须是派生类型.)

If you then want to go back to the derived type, use a dynamic_cast (or static_cast if you're guaranteed it has to be of the derived type.)