1,枚举

1.1 基本使用

#include <iostream>
using namespace std;
// 枚举对应的值为[0,1,2,3]
enum color {red, blue, green, yellow};

int main()
{
    color c;
    c = red;
    cout << c << endl;

    // 整形赋值需要强制类型转换
    c = (color)2;
    cout << c << endl;

    // 超出变量范围不会报错,但是不提倡使用,也不应该依赖该值
    // 是非法的
    c = (color)1024;
    cout << c << endl;

    // 枚举值可自动转换为int
    int n = blue;
    cout << n << endl;

}

// 枚举值不支持除了=之外的其他运算符,比如+,-等。这是不合法的。枚举没有定义这些符号。

1.2 枚举赋初值

#include <iostream>
#include <stdio.h>
using namespace std;
// 枚举对应的值为[0,3,4,0,1]
enum color {red, blue=3, green, yellow=0, orange};
// 从0开始,其中没有赋值的将向前查找最近的有赋值的元素然后自然增长,依次类推
int main()
{
    printf_s("%d %d %d %d %d\n", red, blue, green, yellow, orange);

}

1.3 枚举的范围

// 现代c++可以通过强制类型转换将int值转换为枚举值
// 每个枚举都有其合法的取值范围,其范围为:
// 上限:取大于枚举最大值最小的2的幂值-1,
// 下限:如果为最小值为正数,则下限取0,如果为负数,取小于枚举最小值最大的2的幂值+1,
enum bits {value=-6, one=1, two=2,eight=8};
// bits的合法的上限为:bits最大的值为8,则大于枚举最大值8最小的2的幂为16,-1则为15
// bits的合法下限位:bits最小的值为-6,则小于枚举最小值-6的最大的2的幂为-8,+1则为-7,
//所以bits的合法范围为[-7,15]