Use union to define class : Union Class « Class « C++






Use union to define class

Use union to define class
 
#include <iostream>
using namespace std;

union bits {
  bits(double n);
  void show_bits();
  double d;
  unsigned char c[sizeof(double)];
};

bits::bits(double n)
{
  d = n;
}

void bits::show_bits()
{
  int i, j;

  for(j = sizeof(double)-1; j>=0; j--) {
    cout << "Bit pattern in byte " << j << ": ";
    for(i = 128; i; i >>= 1) 
      if(i & c[j]) cout << "1";
      else cout << "0";
    cout << endl;
  }
}

int main()
{
  bits ob(1991.829);

  ob.show_bits();

  return 0;
}


           
         
  








Related examples in the same category

1.Unions and Classes are Related
2.An anonymous union is a union that has neither a tag name nor any objects specified in its declaration.
3.Anonymous union