如何在枚举上放置范围?

时间:2018-06-15 21:58:54

标签: c++ c++11 enums

我有一个作业,我必须在订单存储字母值中使用枚举。该链接提供here

关于如何使用枚举在常量中设置值范围,我完全不知道。

// What I'm trying to do enum class Letter { A+, A, B+, B, etc... }

但是,我已经遇到了只有' +'在A。

任何帮助都会受到赞赏

2 个答案:

答案 0 :(得分:5)

+不是可以在该上下文中使用的合法字符。使用其他内容,例如A_PLUS

enum class Letter { A_PLUS, A, B_PLUS, B, etc... }

答案 1 :(得分:0)

正如HolyBlackCat所说,你无法为枚举器指定范围。正如R Sahu所说,你不能在标识符中使用+ - 阅读this以了解更多信息。除了预处理器宏/定义(以及单个字母,模板参数)之外,还应避免使用全大写(带或不带下划线)标识符,这也是最佳做法。无论如何,你可以这样做:

enum class Grade { a_plus, a, b_plus, b, ... };

Grade score_to_grade(int score)
{
    return score >= 90 ? Grade::a_plus :
           score >= 80 ? Grade::a :
           score >= 75 ? Grade::b_plus :
           ...
           score >= 50 ? Grade::d :
           Grade::f;
}

? :conditional operator。上面,它更简洁(一旦你习惯了,可读)相当于:

if (score >= 90) return Grade::a_plus;
if (score >= 80) return Grade::a;
...