有人可以解释一下工会在这一行代码中是如何工作的,以及数字是如何交换的

Can someone explain how the union works in this line of code and how the numbers are being swaped?

本文关键字:工作 何工作 交换 何交换 数字 一下 解释 一行 代码      更新时间:2023-10-16
#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是一种

特殊的结构,其中成员重叠,因此swap_byte的布局如下所示:

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

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

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