union的使用
ssk-wh Lv4

union的常见用法…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <stdio.h>
#include <string.h>

struct var_struct{
enum Type{
Int,
Double,
CharArr
};

union {
int iv;
double dv;
char *arr;
};

Type t;

Type type() { return t;}

var_struct(const int &v) :iv{ v }, t(Int) {}
var_struct(const double &v) :dv{ v }, t(Double) {}
var_struct(const char *s) :t(CharArr) {
size_t len = strlen(s);
arr = new char[len +1];
memcpy(arr, s, len + 1);
}

int toInt() {
return iv;
}
double toDouble() {
return dv;
}
char *toCharArr() {
return arr;
}
};

int main(int argc, char *argv[])
{
(void) argc;
(void) argv;

var_struct v1(100);
var_struct v2(12.34);
var_struct v3("hello");
std::cout << v1.type() << " " << v1.toInt() << std::endl;
std::cout << v2.type() << " " << v2.toDouble() << std::endl;
std::cout << v3.type() << " " << v3.toCharArr() << std::endl;
}

输出:

1
2
3
0 100
1 12.34
2 hello
 Comments