Section 7.2 Enumeration declarations 没有说明任何关于 operator!=()
和作用域的 operator==()
枚举。但是下面的代码可以编译。
#include <iostream>
enum class Month{jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov , dec};
int main()
{
Month a = Month::feb;
Month b = Month::jul;
Month c = a;
if( a != b ) std::cout << "a |= b" << '\n';
if( a == c ) std::cout << "a == c" << '\n';
}
内置运算符在 5.10 中指定:
The == (equal to) and the != (not equal to) operators have the same semantic restrictions, conversions, and result type as the relational operators except for their lower precedence and truth-value result.
这将规范推迟到 5.9 中的关系运算符;对于 5.9/5 指定的枚举:
If both operands (after conversions) are of arithmetic or enumeration type, each of the operators shall yield true if the specified relationship is true and false if it is false.
因此,正如人们可能预料的那样,比较运算符适用于枚举,比较数值。
我是一名优秀的程序员,十分优秀!