主要内容

本页翻译不是最新的。点击此处可查看最新英文版本。

AUTOSAR C++14 Rule A7-2-3

Enumerations shall be declared as scoped enum classes

描述

规则定义

Enumerations shall be declared as scoped enum classes.

理由

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

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 未报告该违规,请参阅Diagnose Why Coding Standard Violations Do Not Appear as Expected

示例

全部展开

#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 的注释行所示)。

检查信息

组:声明
类别:必需、自动

版本历史记录

在 R2019b 中推出