CPP-Union的主要用法特性

本文最后更新于:2021年4月7日 晚上

CPP-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
//
// Created by hewei on 2021/4/3.
//

#include <iostream>

union Matrix
{
struct
{
double _a11, _a12, _a13;
double _a21, _a22, _a23;
double _a31, _a32, _a33;
};

double _element[3][3];
};

/**
* Union结构中,是共享存储空间的,所以实际上_element和_a11,...,_a33是同一块区域的数据
* 上述Union结构可以对3x3的矩阵通过_element实现批量处理;
* 也可以通过_a11,...,_a33实现单独元素的处理,避免了一个一个取值的麻烦
*
*/

int main() {
Matrix matrix;
for (int i = 0; i <= 2; ++i) {
for (int j = 0; j <= 2; ++j) {
std::cin >> matrix._element[i][j];
}
}
double v = matrix._a11*matrix._a22*matrix._a33 + matrix._a12*matrix._a23*matrix._a31
+ matrix._a13*matrix._a21*matrix._a32 - matrix._a11*matrix._a23*matrix._a32 +
matrix._a12*matrix._a21*matrix._a33 - matrix._a13*matrix._a22*matrix._a31;
std::cout << "v: " << v << std::flush;
}
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//
// Created by hewei on 2021/4/3.
//

#include <iostream>

enum FIGURE_TYPE {
LINE, RECTANGLE, ELLIPSE
};

struct Line {
FIGURE_TYPE t;
int x1, y1, x2, y2;
};

struct Rectangle {
FIGURE_TYPE t;
int left, top, right, bottom;
};

struct Ellipse {
FIGURE_TYPE t;
int x, y, r;
};

union FIGURE {
FIGURE_TYPE t;
Line line;
Rectangle rect;
Ellipse ellipse;
};

void draw_line(Line line);

void draw_rect(Rectangle rect);

void draw_ellipse(Ellipse ellipse);


int main() {
FIGURE figure;
figure.ellipse = {ELLIPSE, 3, 3, 3};
figure.rect = {RECTANGLE, 2, 2, 2, 2};
figure.line = {LINE, 1, 1, 1, 1};
int t;
while (std::cin >> t) {
switch (t) {
case LINE:
std::cout << figure.line.x1 << std::endl;
draw_line(figure.line);
break;
case RECTANGLE:
std::cout << figure.rect.top << std::endl;
draw_rect(figure.rect);
break;
case ELLIPSE:
std::cout << figure.ellipse.x << std::endl;
draw_ellipse(figure.ellipse);
break;
default:
std::cerr << "No Match Pattern!" << std::flush;
return 0;
}
}
}


void draw_line(Line line) {
std::cout << "Draw Line" << std::endl;
}

void draw_rect(Rectangle rect) {
std::cout << "Draw Rect" << std::endl;
}

void draw_ellipse(Ellipse ellipse) {
std::cout << "Draw Ellipse" << std::endl;
}

1
2
3
4
5
6
7
8
struct Shape{
FIGURE_TYPE type;
union {
Line line;
Rectangle rect;
Ellipse ellipse;
} obj;
};

就不说废话了,自己理解吧!强蔷蔷!!!!

wwww,awsl!


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!