| Bruce Eckel's Thinking in C++, 2nd Ed | Contents | Prev | Next |
//: C07:UnionClass.cpp
// Unions with constructors and member functions
#include<iostream>
using namespace std;
union U {
private: // Access control too!
int i;
float f;
public:
U(int a) { i = a; }
U(float b) { f = b;}
~U() { f = 0; }
int read_int() { return i; }
float read_float() { return f; }
};
int main() {
U X(12), Y(1.9F);
cout << X.read_int() << endl;
cout << Y.read_float() << endl;
} ///:~ //: C07:SuperVar.cpp
// A super-variable
#include <iostream>
using namespace std;
class SuperVar {
enum {
character,
integer,
floating_point
} vartype; // Define one
union { // Anonymous union
char c;
int i;
float f;
};
public:
SuperVar(char ch) {
vartype = character;
c = ch;
}
SuperVar(int ii) {
vartype = integer;
i = ii;
}
SuperVar(float ff) {
vartype = floating_point;
f = ff;
}
void print();
};
void SuperVar::print() {
switch (vartype) {
case character:
cout << "character: " << c << endl;
break;
case integer:
cout << "integer: " << i << endl;
break;
case floating_point:
cout << "float: " << f << endl;
break;
}
}
int main() {
SuperVar A('c'), B(12), C(1.44F);
A.print();
B.print();
C.print();
} ///:~ i = 12; f = 1.22;