gpt4 book ai didi

c++ - 有人可以解释 union 如何在这行代码中工作以及如何交换数字吗?

转载 作者:搜寻专家 更新时间:2023-10-31 00:30:24 24 4
gpt4 key购买 nike

#include<iostream>
using namespace std;
union swap_byte { //This code is for union
public:
void swap();
void show_byte();
void set_byte(unsigned short x);
unsigned char c[2];
unsigned short s;
};

void swap_byte::swap() //swaping the declared char c[2]
{
unsigned char t;
t = c[1];
c[1] = c[0];
c[0] = t;
}
void swap_byte::show_byte()
{
cout << s << "\n";
}
void swap_byte::set_byte(unsigned short x) //input for the byte
{
s = x;
}
int main()
{
swap_byte b;
b.set_byte(49034);
b.show_byte();
b.swap();
b.show_byte();
cin.get();
return 0;
}

我无法理解 union 的用途,我通过上面的代码看到了 union 的实现,但感到困惑,请解释代码的作用以及 union 的工作原理。

最佳答案

union 是一种特殊的结构,其中的成员重叠,因此 swap_byte 的布局类似于:

|     |     | char c[2]
-------------
| | short s

但这发生在相同的 2 个内存字节中。这就是为什么交换 c 的单个字节会产生交换 short 数字中最相关和最不相关字节的效果。

请注意,这可能很脆弱,而且这不是最好的方法,因为您必须确保多个方面。此外,默认情况下,访问与最后一组不同的 union 字段会在 C++ 中产生未定义的行为(但在 C 中是允许的)。这是一个很少用到的老把戏。

关于c++ - 有人可以解释 union 如何在这行代码中工作以及如何交换数字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37194498/

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