正确使用枚举C++

Loc*_*ead 0 c++ enums bit-manipulation

我一直在努力学习如何在C++中正确使用枚举,我几乎无法理解如何处理它们.我做了一个简单的程序,使用枚举和按位操作来改变交通信号灯:

    #include <iostream>

enum lights
{
    green = 1,
    yellow = 2,
    red = 4,
    control = 7
};

std::string change_light (std::string choice)
{
    lights light;
    int changed;

    if (choice == "yellow")
        light = yellow;

    else if (choice == "red")
        light = red;

    else if (choice == "green")
        light = green;

    changed = control & light;

    if (changed == red)
        return "red";

    else if (changed == yellow)
        return "yellow";

    else if (changed == green)
        return "green";
}

int main()
{   
    std::string choice = "";

    while (1)
    {
        std::cout << "What light do you want to turn on?" << std::endl;
        std::cin >> choice;
        std::cout << "Changed to " << change_light(choice) << std::endl;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如何在保持按位操作和枚举的使用的同时改进该程序?如果你能告诉我如何改进它,它将极大地提高我对如何正确使用枚举的理解.

感谢:D

tho*_*ler 5

枚举背后的全部思想是,您可以定义一组常量,为用户和编译器提供有关如何使用变量的一些提示.

你的例子会更有意义,如果change_light函数会采用这样的灯参数:

std::string change_light (lights choice)
{
    switch(choice)
    {
    case red: return "red";
    case yellow: return "yellow";
    case green: return "green";
    }
}
Run Code Online (Sandbox Code Playgroud)

那样编译器知道,该函数只接受某些参数而你不会得到像change_light这样的函数调用("blue")


因此,您使用枚举来保护代码的其余部分免受错误的参数值的影响.你不能直接从std :: in读取枚举,因为它对你的枚举一无所知.阅读后,您应该将输入转换为枚举.像这样的东西:

lights string_to_ligths(std::string choice)
{
    if(choice == "red") return red;
    if(choice == "yellow") return yellow;
    if(choice == "green") return green;
}
Run Code Online (Sandbox Code Playgroud)

从此处开始,所有与红绿灯相关的功能都只接受枚举值,不需要检查请求值是否在有效范围内.