gpt4 book ai didi

c++ - enum 类型是 unscoped 更喜欢 enum 类而不是 enum?

转载 作者:行者123 更新时间:2023-12-05 00:54:25 34 4
gpt4 key购买 nike

我是 C++ 新手,我想知道是否有人可以帮助我理解原因

enum difficulty { NOVICE, EASY, NORMAL, HARD, UNBEATABLE };
difficulty myDiffiuclty = EASY

enum shipCost { FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50 };
shipCost myShipCost = BOMBER_COST;

有绿色下划线吗?它说它更喜欢枚举类,但是当我将其更改为枚举类时

enum class difficulty { NOVICE, EASY, NORMAL, HARD, UNBEATABLE };
difficulty myDiffiuclty = EASY;

enum class shipCost { FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50 };
shipCost myShipCost = BOMBER_COST;

EASY 变为红色下划线,并且myShipCost 用绿色下划线,BOMBER_COST 用红色下划线,CRUISER_COST 用红色下划线

const int ALIEN_POINTS = 150;
int aliensKilled = 10;
int score = aliensKilled * ALIEN_POINTS;
cout << "score: " << score << endl;

enum difficulty { NOVICE, EASY, NORMAL, HARD, UNBEATABLE };
difficulty myDifficulty = EASY;

enum shipCost { FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50 };
shipCost myShipCost = BOMBER_COST;
cout << "\nTo upgrade my ship to a cruiser will cost "
<< (CRUISER_COST - myShipCost) << " Resource Points.\n";

system("pause");
return 0;

最佳答案

enum class difficulty { NOVICE, EASY, NORMAL, HARD, UNBEATABLE };
difficulty myDiffiuclty = difficulty::EASY;

enum class shipCost { FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50 };
shipCost myShipCost = shipCost::BOMBER_COST;

使用 enum 类,与整数的隐式转换被删除,并且你必须在其中限定常量。

这被认为是一种改进。将其显式转换回整数仍然有效,但这不是偶然发生的。

std::cout << "\nTo upgrade my ship to a cruiser will cost "
<< (static_cast<int>(shipCost::CRUISER_COST) - static_cast<int>(myShipCost)) <<
" Resource Points.\n";

system("pause");
return 0;

一旦你使用了enum class,你应该重命名它们:

enum class difficulty { novice, easy, normal, hard, unbeatable };
difficulty myDiffiuclty = difficulty::easy;

enum class shipCost { fighter =25, bomber=30, cruiser = 50 };
shipCost myShipCost = shipCost::bomber;

由于名称的 ship 部分现在在 enum 中,因此无需在常量中重复。同样,由于名称是有范围的,您不必SHOUT它们。

但是请注意,如果您只是使用它来创建常量而不打算创建类型,请考虑使用类似的东西:

namespace ship {
namespace cost {
constexpr int fighter = 25;
constexpr int bomber = 30;
constexpr int cruiser = 50;
}
}

现在我们将 ship::cost::fighter 作为编译时计算的 int,而不是作为 enum 类 .

关于c++ - enum 类型是 unscoped 更喜欢 enum 类而不是 enum?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66360268/

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