C++ Union联合的用法

#include <iostream>
using namespace std;

struct Params
{
	enum ParamsType{INT,CHAR,DBL};
	ParamsType type;
	union
	{
		int intParams;
		char charParams;
		double doubleParams;
	};
	Params(int p){intParams = p;type = INT;}
	Params(char p){charParams = p;type = CHAR;}
	Params(double p){doubleParams = p;type = DBL;}

};

void print(const Params& p)
{
	switch(p.type)
	{
	case Params::INT:
		cout << p.intParams <<endl;
		break;
	case Params::CHAR:
		cout << p.charParams <<endl;
		break;
	case Params::DBL:
		cout << p.doubleParams <<endl;
		break;
	}
}
void main()
{

	Params p1 = 1;
	Params p2('c');
	Params p3 = 1.1;

	print(p1);
	print(p2);
	print(p3);
}

;

Popular Programs