共用体を使ってみる

#include <cstdio>

union Foo {
  Foo(short i);
  void show();

private:
  short i;
  unsigned char cs[2];
};

Foo::Foo(short i) : i(i) {}

void Foo::show() {
  printf("l:%x h:%x\n", cs[0], cs[1]);
}

int main() {
  union {
    short i;
    unsigned char cs[2];
  };

  i = 0xABCD;
  printf("l:%x h:%x\n", cs[0], cs[1]);

  Foo foo(0xCAFE);
  foo.show();

  return 0;
}


~/cpp$ g++ foo.cpp -o foo && ./foo
l:cd h:ab
l:fe h:ca