枚举元素的值取决于定义时各枚举元素排列的先后顺序.默认情况下,第一个枚举元素的值为0,第二个为1,依次顺序加1.
enum Season {
Spring,//0
Summer=2,//2
Autumn,//3
Winter//4
};
enum Season {
Spring,//0
Summer=2,//2
Autumn,//3
Winter=100//100
};
enum Season {
Spring=1,//1
Summer,//2
Autumn=6,//6
Winter//7
};
#include<iostream>
#include<string>
using namespace std;
//常用第一种方式
//第一种方式:
enum Season {
Spring,//0
Summer,//1
Autumn,//2
Winter//3
};
/*
//第二种方式:
enum Season {
Spring,//0
Summer,//1
Autumn,//2
Winter//3
}s;
*/
/*
//第三种方式:
enum {
Spring,//0
Summer,//1
Autumn,//2
Winter//3
}s1,s2;
*/
int main(void) {
enum Season s;
s = Spring;
//s=0;不可把整数直接赋值给枚举变量
//s = (enum Season)3;//强制类型转换可能存在风险
enum Season s2;
s2 = Winter;
printf("s= %d\n", s);//0
printf("s2=%d\n", s2);//3
printf("enum Season:%d", sizeof(enum Season));//4
system("pause");
return 0;
}