C ++联合位字段任务

hig*_*der 5 c++

有人可以弄清楚我为什么要使用并集,并且为cin'ed变量和位字段(Schildts C ++书中的任务)使用相同的地址是什么目的?换句话说,我为什么要使用union:

char ch; 结构字节位;

//显示二进制的ASCII码字符。

#include <iostream>
#include <conio.h>
using namespace std;

// a bit field that will be decoded
struct byte {
  unsigned a : 1;
  unsigned b : 1;
  unsigned c : 1;
  unsigned d : 1;
  unsigned e : 1;
  unsigned f : 1;
  unsigned g : 1;
  unsigned h : 1;
};

union bits {
  char ch;
  struct byte bit;
} ascii ;

void disp_bits(bits b);

int main()
{
  do {
    cin >> ascii.ch;
    cout << ": ";
    disp_bits(ascii);
  } while(ascii.ch!='q'); // quit if q typed

  return 0;
}

// Display the bit pattern for each character.
void disp_bits(bits b)
{
  if(b.bit.h) cout << "1 ";
    else cout << "0 ";
  if(b.bit.g) cout << "1 ";
    else cout << "0 ";
  if(b.bit.f) cout << "1 ";
    else cout << "0 ";
  if(b.bit.e) cout << "1 ";
    else cout << "0 ";
  if(b.bit.d) cout << "1 ";
    else cout << "0 ";
  if(b.bit.c) cout << "1 ";
    else cout << "0 ";
  if(b.bit.b) cout << "1 ";
    else cout << "0 ";
  if(b.bit.a) cout << "1 ";
    else cout << "0 ";
  cout << "\n";
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ins 5

作为一个联合,两者chbit具有重叠(共享)的内存位置。将字符存储为ch,然后读取bit产生该字符的相应位值。

  • C ++表示这样做是不确定的。我不清楚如果您使用联合的副本来执行第二个操作是否仍未定义。 (2认同)

小智 5

真正的答案是 - 你不会。像这样在联合(或根本)中使用位域本质上是不可移植的,并且可能是未定义的。如果您需要摆弄位,最好使用 C++ 按位运算符。