c++ - 哪些运算符是为作用域枚举自动定义的?

标签 c++ enums operators

对于无作用域枚举,答案是“大多数”,因为隐式转换为基础整数类型。但是,作用域枚举没有这种隐式转换。相反,为它们定义了一些但不是所有可用于无作用域枚举的运算符。

#include <iostream>

enum class Color{
    Red,
    Green,
    Blue
};

int main()
{
    std::cout << (Color::Red < Color::Green) << '\n';
    // Fine, operator< is defined for Color
    std::cout << (Color::Red + Color::Green == Color::Green) << '\n';
    // no match for 'operator+'
}
我的猜测是关系运算符已定义,但算术运算符未定义,但我没有看到任何明确说明 the cppreference page并且还没有进行实际的标准潜水,以了解 C++ 对此事的看法。

最佳答案

关系运算符通过 选择加入[expr.rel]

The usual arithmetic conversions are performed on operands of arithmetic or enumeration type. If both operands are pointers, pointer conversions and qualification conversions are performed to bring them to their composite pointer type. After conversions, the operands shall have the same type.


算术运算符由 ommision 选择退出。例如: [expr.add]

the left operand is a pointer to a completely-defined object type and the right operand has integral or unscoped enumeration type.

关于c++ - 哪些运算符是为作用域枚举自动定义的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68534699/

相关文章:

c++ - 如何让我的圈子用键移动

c++ - BOOST_SCOPE_EXIT 在幕后做了什么?

c++ - 矩阵乘法问题

c++ - 通过函数创建 unique_ptr

c - 枚举名称有什么作用?

c - 将文件读入包含 C 中枚举的 typedef 结构?

enums - Kotlin 中具有反向查找的有效枚举?

c++ - while循环C++中的多个条件

C++ - 将运算符存储为 char

java - java中的 ">>"和 ">>>"运算符是什么?