枚举类型enum
enum枚举类型:在实际问题中,有些变量的取值被限定在一个有限的范围内。例如,一个星期内只有七天,一年只有十二个月,一个班每周有六门课程等等。如果把这些量说明为整型,字符型或其它类型显然是不妥当的。为此,C语言提供了一种称为“枚举”的类型。在“枚举”类型的定义中列举出所有可能的取值,被说明为该“枚举”类型的变量取值不能超过定义的范围。应该说明的是,枚举类型是一种基本数据类型,而不是一种构造类型,因为它不能再分解为任何基本类型。
enum是枚举型 union是共用体,成员共用一个变量缓冲区
#include <iostream>
using namespace std;
void main()
{
enum open_modes {input, output, append};
enum Forms {shape = 1, sphere, cylinder, polygon};
cout<<"sizeof(open_modes) == "<<sizeof(open_modes)<<endl;
cout<<"sizeof(Forms) == "<<sizeof(Forms)<<endl;
cout<<"sizeof(int) == "<<sizeof(int)<<endl;
//open_modes om = 1;// error
open_modes om = (open_modes)1;
//int t = open_modes::input;
int t = input;
int k = sphere;
cout<<"om == "<<om<<" t == "<<t<<" k == "<<k<<endl;
open_modes om2 = (open_modes)100;
cout<<"om2 == "<<om2<<endl;
}
输出:

最后更新:2017-04-03 05:39:09