来自父结构的C++覆盖数据不起作用

vlk*_*vlk 0 c++ inheritance struct

通常它没有意义并且非常不安全,但理论上只有有办法,

这是一个例子:

#include<iostream>

struct A {
    uint32_t &get() {
        return *reinterpret_cast<uint32_t *>(this);
    }

    void set(const uint32_t val) {
        *this = *reinterpret_cast<const A *>(&val);
    }
};

struct B : A {
    uint16_t a;
    uint16_t b;

    void set_b(const uint32_t val) {
        *this = *reinterpret_cast<const B *>(&val);
    }
};

main() {
    B k;
    k.a = 0x1234;
    k.b = 0x5678;
    std::cout << std::hex << k.get() << " : " << k.a << " " << k.b << std::endl;
    k.set_b(0x87654321);
    std::cout << std::hex << k.get() << " : " << k.a << " " << k.b << std::endl;
    k.set(0xaabbccdd);
    std::cout << std::hex << k.get() << " : " << k.a << " " << k.b << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

我得到这个结果:

56781234 : 1234 5678
87654321 : 4321 8765
87654321 : 4321 8765
Run Code Online (Sandbox Code Playgroud)

但我除了最后应该是:

aabbccdd : ccdd aabb
Run Code Online (Sandbox Code Playgroud)

那么,为什么从父母那里覆盖结构中的数据不起作用呢?

实验:

我做了一个实验,我在struct A中添加了一个变量,然后set function按预期工作(但最终结构更大)

当然,有不同的方法来处理这个问题(例如与工会有关),但我只是玩这个,我感兴趣的是为什么这不起作用.

Som*_*ude 5

在课堂上,A这个set功能真的很棒

void set(const uint32_t val) {
    (*this).operator=(*reinterpret_cast<const A *>(&val));
}
Run Code Online (Sandbox Code Playgroud)

这将调用自动生成的A::operator=函数.但由于A没有任何成员变量需要复制,它什么都不做.


现在你已经完成了实验,请不要再做那样的事了.