从void *转换为基类的指针 [英] Conversion from void* to the pointer of the base class

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

问题描述

我有一些层次结构:基本,派生类和一些结构存储用户数据作为void *。该void可以存储Base和Derived类指针。主要问题,我不知道什么是存储基地或派生指针。

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; // init base pointer
Derived * derived; init派生指针
void * base_v = base;
void * derived_v = derived;
// void指针是正确的。

Base* base;//init base pointer Derived* derived;//init derived pointer void* 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正确
基本* b_restored =(基本*)base_v; // b_restored正确
基本* d_restored_to_base =(基本*)derived_v; // INCORRECT

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

code>

如何转换void *来获取两个指针的[type]字段?
提前感谢。

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

推荐答案

void * 只能转换回原来的类型。当您在 void * 中存储 Derived * 时,只能回复到 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 << "\n";
    std::cout << "bad: " << b2->type << "\n";
}

如果你想回到派生类型, c $ c> 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 *转换为基类的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆