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