主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

MISRA C++:2023 Rule 10.2.2

Unscoped enumerations should not be declared

自 R2024b 起

描述

规则定义

Unscoped enumerations should not be declared. 1

理由

无限定作用域的枚举中的枚举值可能会与枚举作用域中的其他标识符发生冲突,并导致编译错误。例如:

enum E: std::int32_t { E0, E1};
std::int32_t E0;

如果您限定了枚举的作用域,则可以避免此类冲突。例如:

enum class E: std::int32_t { E0, E1};
std::int32_t E0;

限定枚举作用域还禁止将枚举值隐式转换为其他类型。

Polyspace 实现

Polyspace® 会报告您的代码中未限定作用域的枚举违规。类中的未限定枚举不会被报告为违反此规则。

故障排除

如果您预期会出现违规,而 Polyspace 未报告该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

#include<cstdint>

enum E1: std::int32_t { E10, E11}; //Noncompliant
// std::int32_t E10; causes compilation errors

enum class E2: std::int32_t { E20, E21}; //Compliant
std::int32_t E20;

在此示例中,无限定作用域的枚举 E1 的声明不合规。重新声明无限定作用域的枚举的枚举值会导致编译错误(如重新声明枚举值 E10 的注释行所示)。

检查信息

组:声明
类别:建议

版本历史记录

在 R2024b 中推出


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.