// unions.cpp
// Defines and uses a union.
// ---------------------------------------------------
#include <iostream>
using namespace std;
union WordByte
{
private:
unsigned short w;
unsigned char b[2]; // an array member of size 2?
public:
unsigned short& word() { return w; } // public methods have access to the private members
unsigned char& lowByte() { return b[0]; }
unsigned char& highByte(){ return b[1]; }
};
int main()
{
WordByte wb; // create an instance of WordByte with name wb
wb.word() = 256; // access the public members .word()
cout << "\nWord:" << (int)wb.word(); // access the public members .word(), transfer the returned value to int type
cout << "\nLow-byte: " << (int)wb.lowByte() // access the public members .lowByte(), explicit casting
<< "\nHigh-byte: " << (int)wb.highByte() // access the public members .highByte(), explicit casting
<< endl;
return 0;
}
Hi, the above code is excepted from the book a complete guide to c++. When I run it, the following is the output:
~$ g++ units.cpp
~$ ./a.out
Word:256
Low-byte: 0
High-byte: 1
I understand why the output 256. But why 0 and 1 in the output?