妙用union和enum实现只有一个数据成员的类可存储不同的类型

直接上代码:

// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 1999
// Copyright notice in Copyright.txt
// 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();
}



联合也可以有构造函数、析构函数、成员函数甚至访问控制,它与class的唯一不同之处在于存储数据的方式,观察如下代码:

// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 1999
// Copyright notice in Copyright.txt
// 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;
}


你可能感兴趣的:(c,Integer,存储,Access,character,float)