Union 联合

#ifndef SUPERVAR_H_
#define SUPERVAR_H_

class SuperVar  
{
	enum     // 枚举 后边的标识符可以不写即为匿名的,
	{
		character,
		integer,
		floating_point
	}varType; // 这里的varType 是class的成员变量,
	union           // 这个就是使用类封装联合,后边的标识符可以不写即为匿名的,
	{
		char c;
		int i;
		float f;
	};
public:
	SuperVar(char ch);
	SuperVar(int in);
	SuperVar(float fl);
	~SuperVar();
	void print();
};

#endif

#include "SuperVar.h"
#include <iostream>

using namespace std;

SuperVar::SuperVar(char ch)
{
	c = ch;
	varType = character;  // 这个是为了定义类型,记录保存的类型用枚举来表示,
}

SuperVar::SuperVar(int in)
{
	i = in;
	varType = integer;
}

SuperVar::SuperVar(float fl)
{
	f = fl;
	varType = floating_point;
}

SuperVar::~SuperVar()
{
	
}

void SuperVar::print()
{
	switch (varType)
	{
	case SuperVar::character:
		cout << "character: " << c << endl;
		break;
	case SuperVar::integer:
		cout << "integer: " << i << endl;
		break;
	case SuperVar::floating_point:
		cout << "floating_point: " << f << endl;
		break;
	default:
		break;
	}
}

#ifndef UNIONCLASS_H_
#define UNIONCLASS_H_

union U    // union 联合,里边的成员共有存储空间,可以节省存储空间,
{
private:
	int i;
	float f;
public:
	U(int a);
	U(float b);
	~U();
	int read_int();
	float read_float();
};

#endif

#include "UnionClass.h"
#include <iostream>

using namespace std;

U::U(int a) { i = a; }
U::U(float b) { f = b; }
U::~U() { cout << " ~U 被调用." << endl; }
int U::read_int() { return i; }
float U::read_float() { return f; }

#include <iostream>
#include "UnionClass.h"
#include "SuperVar.h"

using namespace std;

int main()
{
	U X(12), Y(31.0f);
	cout << X.read_int() << endl;
	cout << Y.read_float() << endl;

	SuperVar A('a'), B(1314), C(12.31f);
	A.print();
	B.print();
	C.print();

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值