枚举类型}+变量名是什么意思呢

在enum{} 后加变量type什么意思呢?
以及在联合体最后}value什么意思呢?
0: #include <iostream>
1: using namespace std;
2:
3: union SimpleUnion
4: {
5: int num;
6: char alphabet;
7: };
8:
9: struct ComplexType
10: {
11: enum DataType
12: {
13: Int,
14: Char
15: } Type;
16:
17: union Value
18: {
19: int num;
20: char alphabet;
21:
22: Value() {}
23: ~Value() {}
24: }value;
25: };
26:
27: void DisplayComplexType(const ComplexType& obj)
28: {
29: switch (obj.Type)
30: {
31: case ComplexType::Int:
32: cout << "Union contains number: " << obj.value.num << endl;
33: break;
34:
35: case ComplexType::Char:
36: cout << "Union contains character: " << obj.value.alphabet << endl;
37: break;
38: }
39: }
40:
41: int main()
42: {
43: SimpleUnion u1, u2;
44: u1.num = 2100;
45: u2.alphabet = 'C';
46: cout << "sizeof(u1) containing integer: " << sizeof(u1) << endl;
47: cout << "sizeof(u2) containing character: " << sizeof(u2) << endl;
48:
49: ComplexType myData1, myData2;
50: myData1.Type = ComplexType::Int;
51: myData1.value.num = 2017;
52:
53: myData2.Type = ComplexType::Char;
54: myData2.value.alphabet = 'X';
55:
56: DisplayComplexType(myData1);
57: DisplayComplexType(myData2);
58:
59: return 0;
60: }












#笔试题目##C/C++#
全部评论
书上的 希望有大神能解答一下
点赞 回复
分享
发布于 2019-05-24 17:51
最后运行结果是: sizeof(u1) containing integer: 4 sizeof(u2) containing character: 4 Union contains number: 2017 Union contains character: X
点赞 回复
分享
发布于 2019-05-24 17:58
百信银行
校招火热招聘中
官网直投
enum {...}定义了一个具体的枚举类型,后面加变量名就是定义了这个类型的枚举变量。结构体、联合体都是一样的。 struct Object { // ... } object;和 struct Object { // ... }; Object object;是一样的,不过在C语言里表示结构体类型需要加上struct,比如像struct Object object;是定义,所以经常会这样简化代码,或者写出 typedef struct object { // ... } Object;这种代码,结构体名称首字母小写,但是别名是大写,也就是struct object和Object是等价的,而在C++中就不需要特地加上struct修饰类型。
点赞 回复
分享
发布于 2019-05-24 17:58
struct ComplexType { enum DataType { Int, Char } Type; // ... };Type是结构体ComplexType的成员变量,它的类型是枚举类型DataType,而这个枚举类型是嵌套在结构体ComplexType内的,因此需要用ComplexType::Int来表示枚举常量Int。如果枚举类型不是嵌套在结构体内,参考以下代码 // 枚举类型的定义 enum DataType { Int, Char } type; // 变量type的类型是enum DataType // 以下是对type的操作 type = Int; // 将枚举值Int赋值给变量type DataType type2 = Char; // 将枚举值Char赋值给变量type回到楼主的代码上 myData1.Type = ComplexType::Int; Type变量是定义在结构体内的成员变量,myData1是一个结构体变量,因此用myData1.Type表示这个结构体变量的Type成员; Int是枚举类型DataType1的一个枚举值,而该枚举类型是嵌套在结构体ComplexType内的,所以枚举值也是嵌套在结构体ComplexType内,因此用ComplexType::Int表示这个枚举值。
点赞 回复
分享
发布于 2019-05-25 01:38

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务