有人可以解释一下工会在这一行代码中是如何工作的,以及数字是如何交换的
Can someone explain how the union works in this line of code and how the numbers are being swaped?
#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 中是允许的(。这是一个很少需要的老把戏。
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 当 int 方法工作正常时,void 方法有何不同,或者为什么我不能调用 void 方法?
- sdl软件渲染器不工作,工作在硬件加速的一个