Issue in reinterpret_cast


struct A
{
uint8_t hello[3]; 
};
struct B
{
const struct C* hello;
};
struct C
{
uint8_t hi[3];
};
B.hello = &reinterpret_cast<C &>(A);

假设我用值1,2,3填充结构A。如果我输出B.hello.hi[0],我得到0。相反,我应该得到1。我选角做错了吗?

我已经检查了结构体A在我的代码reinterpret_cast行上方的值,它打印ok,所以我不认为我在A中存储值有任何问题。这就是导致问题的转换。

强制类型转换适用于实例而不是类,因此您需要强制类型转换A的实例而不是A本身

#include <cstdint>
#include <cassert>
struct A
{
uint8_t hello[3];
};
struct B
{
const struct C* hello;
};
struct C
{
uint8_t hi[3];
};

int main()
{
A a{}; 
a.hello[0] = 1;
a.hello[1] = 2;
a.hello[2] = 3;
B b{};
b.hello = reinterpret_cast<C*>(&a);
auto hi = b.hello->hi;
assert(hi[2] == 3);
}

最新更新