到基类指针的转换

到基类指针的转换

本文介绍了从 void* 到基类指针的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些层次结构:基类、派生类和一些将用户数据存储为 void* 的结构.该 void 可以存储基类和派生类指针.主要问题是我不知道那里存储的是基指针还是派生指针.

I have some hierarchy: base, derived classes and some structure storing user data as void*. That void can store both Base and Derived classes pointers. Main problem that I do not know what is stored there base or derived pointer.


class Base
{
public:
  int type;
};
class Derived: public Base
{};

Base* base;//初始化基指针派生*派生;//初始化派生指针void* base_v = base;无效 * 派生_v = 派生;//void 指针是正确的.它们指向基础变量和派生变量.

Base* base;//init base pointerDerived* derived;//init derived pointervoid* base_v = base;void* derived_v = derived;//void pointers are correct. They point to base and derived variables.

//将指针转换回来后尝试获取类型字段Derived* d_restored = (Derived*)derived_v;//d_restored 正确Base* b_restored = (Base*)base_v;//b_restored 正确Base* d_restored_to_base = (Base*)derived_v;//错误

//try to get type field after converting pointers backDerived* d_restored = (Derived*)derived_v;//d_restored correctBase* b_restored = (Base*)base_v;//b_restored correctBase* d_restored_to_base = (Base*)derived_v;// INCORRECT

如何将 void* 转换为两个指针的 [type] 字段?提前致谢.

How to convert void* to get [type] field for both pointers?Thanks in advance.

推荐答案

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.)

这篇关于从 void* 到基类指针的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 21:35