gpt4 book ai didi

c++ - 正确使用枚举 C++

转载 作者:太空宇宙 更新时间:2023-11-04 15:09:27 25 4
gpt4 key购买 nike

我一直在努力学习如何在 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;
}

如何在保留按位运算和枚举的同时改进该程序?如果您能告诉我如何改进它,那将大大提高我对如何正确使用枚举的理解。

谢谢:D

最佳答案

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

如果 change_light 函数采用这样的 lights 参数,您的示例会更有意义:

std::string change_light (lights choice)
{
switch(choice)
{
case red: return "red";
case yellow: return "yellow";
case green: return "green";
}
}

这样编译器就知道,函数只接受某些参数,你不会得到像 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;
}

从这里开始,所有与交通灯相关的函数都只接受枚举值,不需要检查请求值是否在有效范围内。

关于c++ - 正确使用枚举 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5132982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com