Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 枚举的运算符重载_C++_Enums_Operators - Fatal编程技术网

C++ 枚举的运算符重载

C++ 枚举的运算符重载,c++,enums,operators,C++,Enums,Operators,是否可以为枚举定义运算符?例如,我班上有enum Month,我希望能够编写++my_Month。 谢谢 附加说明 为了避免溢出,我做了如下操作: void Date::add_month() { switch(my_month_) { case Dec: my_month_ = Jan; add_year(); break; default: ++my_month_; break;

是否可以为枚举定义运算符?例如,我班上有enum Month,我希望能够编写++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;
}
enum月
{
一月,,
二月,,
//…剪断。。。
十二月
};
//前缀(++我的月)
月和操作员++(月和起始)
{
orig=static_cast(orig+1);//需要static_cast,因为enum+int->int
//!!!!!!!!!!!
//待办事项:见下面答案的其余部分
//!!!!!!!!!!!
返回原点;
}
//后缀(我的月份++)
月运算符++(月和起始,整数)
{
月rVal=orig;
++奥利格;
返回rVal;
}
但是,您必须决定如何处理枚举的“溢出”。如果my_month等于December,并且您执行语句
++my_month
,my_month在数字上仍将与December+1相等,并且在枚举中没有相应的命名值。如果您选择允许这样做,则必须假设枚举的实例可能超出范围。如果您选择在递增之前检查
orig==December
,则可以将该值包装回一月并消除此问题。然而,你已经失去了你在新的一年里积累的信息


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

Month&operator++(Month&en){en=static\u cast(static\u cast(en)+1);return en;}谢谢您的代码。如果月份已经是12月了,我们只需要考虑函数应该做什么。模任何人?@Stephen:你不需要强制转换为int,枚举会隐式地转换为int(或更大,如果必要的话)进行算术运算。