共同体
共同体能够存储不同的数据类型, 但是在同一时间只能存储其中一种类型。
- 共同体占用的内存大小是其内部最大的成员占用内存大小
- 全部的成员使用同一块内存
- 共同体中的值为最后被赋值的那个成员的值
- 可以在定义共同体的时候创建共同体变量,也可以嵌入结构体中。
#include <iostream>
using namespace std;
union data {
int a;
double b;
char c[21];
};
int main() {
union data d;
cout << "sizeof(data) = "<<sizeof(d)<<endl;
cout << "d.a的地址 = "<<(void *)&d.a<<endl;
cout << "d.b的地址 = "<<(void *)&d.b<<endl;
cout << "d.c的地址 = "<<(void *)&d.c<<endl;
return 0;
}
![](https://img.haomeiwen.com/i13167756/4a49b0d0552db149.png)
枚举
- 用枚举创建的变量取值只能在枚举量范围内。
- 枚举的作用域与变量的作用域相同
- 可以显式的设置枚举量的值(必须是整数)
enum colors{red=0, green=1 ,blue=2, other=3}; - 也可以显式的指定某些枚举量的值(枚举量的值可以重复)
enum colors{red, green=10 ,blue, other}; // red为0 green=10 blue=11 other=12 - 可以将整数强制转换成枚举量, 语法:枚举类型(整数)
int main() {
enum colors{red=0, green=1 ,blue=2, other=3};
cout << "red:"<<red<<" green:"<<green<<" blue:"<<blue<<" other:"<<other <<endl;
colors col = other;
// colors col2 = colors(3); 将整数强制转换成枚举量
switch (col)
{
case red: cout << "红色" <<endl; break;
case green: cout << "红色" <<endl; break;
case blue: cout << "红色" <<endl; break;
default: cout << "未知" <<endl;
}
return 0;
}
![](https://img.haomeiwen.com/i13167756/5d0b321a9a4301f1.png)
网友评论