gpt4 book ai didi

c++ - C++中的 union (请解释一下)

转载 作者:行者123 更新时间:2023-12-01 15:12:25 26 4
gpt4 key购买 nike

#include <iostream>

#define print(x) std::cout << x
#define println(x) std::cout << x << std::endl

struct Vector2 {
float x, y;
};

struct Vector4 {
union {
struct {
float x, y, z, w;
};
struct {
Vector2 a, b;
};
};
};

void PrintVector2(const Vector2& vector) {
println(vector.x << ", " << vector.y);
}

int main() {
Vector4 vector = { 1, 2, 3, 4 };
vector.x = 2;
vector.z = 500.0f;
PrintVector2(vector.a);
PrintVector2(vector.b);
}
任何人都可以解释这段代码中发生了什么吗?,我不明白什么是联合
以及它们如何工作:/!
这是输出
2, 2
500, 4

最佳答案

代码的行为是不确定的。
这仅是精心设计的un-pun。 C++标准不允许这样做,因为C++ union具有 Activity 成员的概念。设置 Activity 成员后,您将无法以定义的方式读取其他成员。 (您当然可以通过重新分配来更改 Activity 成员。)
谷歌用我用斜体表示的术语吗:在这里更深入地讲毫无意义。

关于c++ - C++中的 union (请解释一下),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63345093/

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