#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;
}