c++ - 以下代码中的变量 b 是什么以及 c++ 中联合的可能好处是什么?
问题描述
// unions.cpp
// Defines and uses a union.
// ---------------------------------------------------
#include <iostream>
using namespace std;
union WordByte
{
private:
unsigned short w; // 16 bits
unsigned char b[2]; // Two bytes: b[0], b[1]
public: // Word- and byte-access:
unsigned short& word()
{ return w; }
unsigned char& lowByte() { return b[0]; }
unsigned char& highByte(){ return b[1]; }
};
int main()
{
WordByte wb;
wb.word() = 256;
cout << "\nWord:" << (int)wb.word();
cout << "\nLow-byte: " << (int)wb.lowByte()
<< "\nHigh-byte: " << (int)wb.highByte()
<< endl;
return 0;
}
我希望这不是一个幼稚的问题。在上面的代码中,这个变量/对象 b 究竟是什么?此外,如何理解工会?你能举个例子来说明它的好处吗?确实非常感谢任何评论。
解决方案
推荐阅读
- weblogic - Weblogic 优雅关闭仍接受新连接
- r - R Shiny Value Function 未在 reactivePoll 中触发
- jquery - 如何解决这个问题?找不到类
- haskell - Haskell,HDBC.Sqlite3 - 如果列不存在,如何添加?
- c# - 排序列表
包括按日期的日期值 - amazon-web-services - Hadoop单节点集群减慢AWS实例
- python - Python3函数不返回完整列表
- python-3.x - 在新的终端窗口中运行 SH 脚本
- sql - 如何使用行号更新表列
- asp.net - 使用 Masterpage 在 .NET Web 窗体中设置引用