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); U(float b); ~U(); int read_int(); float read_float(); }; U::U(int a) { i = a; } U::U(float b) { f = b;} U::~U() { cout << "U::~U()\n"; } int U::read_int() { return i; } float U::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); SuperVar(int ii); SuperVar(float ff); void print(); }; SuperVar:: SuperVar(char ch) { vartype = character; c = ch; } SuperVar:: SuperVar(int ii) { vartype = integer; i = ii; } SuperVar:: SuperVar(float ff) { vartype = floating_point; f = ff; } 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;