gpt4 book ai didi

c++ - 从 void* 到基类指针的转换

转载 作者:可可西里 更新时间:2023-11-01 15:39:20 28 4
gpt4 key购买 nike

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


class Base
{
public:
int type;
};
class Derived: public Base
{};<p></p>

<p>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.</p>

<p>//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
</p>

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

最佳答案

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

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

#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";
}

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

关于c++ - 从 void* 到基类指针的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5445105/

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