gpt4 book ai didi

c++ - 枚举缺失导致编译器出错

转载 作者:行者123 更新时间:2023-11-28 02:21:10 25 4
gpt4 key购买 nike

遵循 here 中的代码:

enum class OS_type { Linux, Apple, Windows };

const std::string ToString(OS_type v)
{
switch (v)
{
case Linux: return "Linux";
case Apple: return "Apple";
case Windows: return "Windows";
default: return "[Unknown OS_type]";
}
}

我想删除 default 并强制编译器在我的枚举上的切换未完成时生成错误。

最佳答案

海湾合作委员会/ clang

您正在寻找-Wswitch-enum .

Warn whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration. case labels outside the enumeration range also provoke warnings when this option is used. The only difference between -Wswitch and this option is that this option gives a warning about an omitted enumeration code even if there is a default label.

const std::string ToString(OS_type v)
{
// warning: enumeration value 'Windows' not handled in switch [-Wswitch-enum]
switch (v)
{
case OS_type::Linux: return "Linux";
case OS_type::Apple: return "Apple";
default: return "[Unknown OS_type]";
}
}

即使使用默认值,它也会提示缺少 Windows 枚举。只需创建适用于 Windows 的案例,然后通过默认设置来取消枚举。

Visual Studio

VS 在编译器级别 3 和 4 处理此问题。您需要启用警告 C4061/C4062https://msdn.microsoft.com/en-US/library/96f5t7fy.aspx

关于c++ - 枚举缺失导致编译器出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32419201/

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