作者:qwer | 来源:互联网 | 2022-12-10 14:11
通常它没有意义并且非常不安全,但理论上只有有办法,
这是一个例子:
#include
struct A {
uint32_t &get() {
return *reinterpret_cast(this);
}
void set(const uint32_t val) {
*this = *reinterpret_cast(&val);
}
};
struct B : A {
uint16_t a;
uint16_t b;
void set_b(const uint32_t val) {
*this = *reinterpret_cast(&val);
}
};
main() {
B k;
k.a = 0x1234;
k.b = 0x5678;
std::cout <
我得到这个结果:
56781234 : 1234 5678
87654321 : 4321 8765
87654321 : 4321 8765
但我除了最后应该是:
aabbccdd : ccdd aabb
那么,为什么从父母那里覆盖结构中的数据不起作用呢?
实验:
我做了一个实验,我在struct A中添加了一个变量,然后set function按预期工作(但最终结构更大)
当然,有不同的方法来处理这个问题(例如与工会有关),但我只是玩这个,我感兴趣的是为什么这不起作用.
1> Some program..:
在课堂上,A
这个set
功能真的很棒
void set(const uint32_t val) {
(*this).operator=(*reinterpret_cast(&val));
}
这将调用自动生成的A::operator=
函数.但由于A
没有任何成员变量需要复制,它什么都不做.
现在你已经完成了实验,请不要再做那样的事了.