gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:54:37 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com