c++ - 运算符为枚举重载

标签 c++ enums operators

是否可以为枚举定义运算符?例如,我的类(class)中有枚举月份,我希望能够编写++my_month。
谢谢
附言
为了避免溢出,我做了这样的事情:

void Date::add_month()
{
    switch(my_month_)
    {
    case Dec:
        my_month_ = Jan;
        add_year();
        break;
    default:
        ++my_month_;
        break;
    }
}

最佳答案

是的,你可以:

enum Month
{
  January,
  February,
  // ... snip ...
  December
};

// prefix (++my_month)
Month& operator++(Month& orig)
{
  orig = static_cast<Month>(orig + 1); // static_cast required because enum + int -> int
  //!!!!!!!!!!!
  // TODO : See rest of answer below
  //!!!!!!!!!!!
  return orig;
}

// postfix (my_month++)
Month operator++(Month& orig, int)
{
  Month rVal = orig;
  ++orig;
  return rVal;
}

但是,您必须决定如何处理“溢出”您的枚举。如果 my_month 等于 December,并且您执行语句 ++my_month,my_month 仍将在数值上等同于 December + 1,并且在枚举中没有相应的命名值。如果您选择允许这样做,您必须假设枚举的实例可能超出范围。如果您选择在递增之前检查 orig == December,您可以将该值回绕到一月并消除此问题。但是,然后,您就丢失了已滚动到新的一年的信息。

TODO 部分的实现(或不实现)将在很大程度上取决于您的个人用例。

关于c++ - 运算符为枚举重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2571456/

相关文章:

c++ - 用于图像处理的 OpenCV 神经网络

c++ - 了解 C++ 0x 特性

c# - 通过自定义属性获取枚举(通用)

c++ - 为什么有些 libstdc++ 迭代器有 operator++ 但没有 operator+?

c++ - 从指针转换为引用

c++ - C onnx header 找不到 OrtEnv 定义

C++:在类内、类外应用枚举

java - Spring MVC 表单 :radiobuttons tag not setting value attribute

php - 是否有令人信服的理由在比较运算中使用 PHP 的运算符 ===,而不是 ==?

需要 Java 运算符 "not equal to"帮助