C++ 标准没有说明枚举类的 operator!=() 和 operator==()

标签 c++ c++11 enums operator-overloading language-lawyer

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.

因此,正如人们可能预料的那样,比较运算符适用于枚举,比较数值。

关于C++ 标准没有说明枚举类的 operator!=() 和 operator==(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22609342/

相关文章:

c++ - QGraphicsItem::boundingRect () 被重复调用?

c++ Valgrind : Address 0x0 is not stack'd, malloc'd 或(最近)free'd

c++ - 两个 std::vectors 指向几乎相同的数据,这可能吗

java - hibernate 枚举中多对多映射的条件限制如何

java - 按序数选择枚举; java

grails - 如何获得常规混合的目标类?

c++ - 在不创建项目的情况下使用eclipse CDT

c++ - 使用与静态库相同的头文件

c++ - 在一个线程中创建对象并使用 std::atomic 访问另一个线程

c++ - 使用 gcc 的别名模板替换和推断失败