首页 > 解决方案 > 以下代码中的变量 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 究竟是什么?此外,如何理解工会?你能举个例子来说明它的好处吗?确实非常感谢任何评论。

标签: c++

解决方案


推荐阅读