运算符重载枚举

The*_* do 12 c++ enums operators

是否可以为枚举定义运算符?例如,我在课堂上有枚举月份,我希望能够写出++ my_month.
谢谢
PS
为了避免溢出我做了这样的事情:

void Date::add_month()
{
    switch(my_month_)
    {
    case Dec:
        my_month_ = Jan;
        add_year();
        break;
    default:
        ++my_month_;
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

Pat*_*yer 17

是的你可以:

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;
}
Run Code Online (Sandbox Code Playgroud)

但是,您必须决定如何处理"溢出"您的枚举.如果my_month等于12月,并且您执行该语句++my_month,则my_month仍将在数字上等效于12月+ 1并且在枚举中没有相应的命名值.如果您选择允许此操作,则必须假设枚举的实例可能超出范围.如果您orig == December在增加它之前选择检查,则可以将值包装回1月并消除此问题.然而,然而,你已经失去了你已经翻新到新的一年的信息.

TODO部分的实施(或缺乏)将在很大程度上取决于您的个人用例.


sel*_*tze 13

是的.可以对所有用户定义的类型执行运算符重载.这包括枚举.

  • Month&operator ++(Month&en){en = static_cast <Month>(static_cast <int>(en)+ 1); 返回; } (2认同)