是否可以为枚举定义运算符?例如,我在班上有枚月,我希望能写出++ my_month
由于
附:
为了避免溢出,我做了类似的事情:
void Date::add_month()
{
switch(my_month_)
{
case Dec:
my_month_ = Jan;
add_year();
break;
default:
++my_month_;
break;
}
}
答案 0 :(得分:14)
是的,你可以:
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等于12月,并且您执行语句++my_month
,则my_month仍将在数字上等效于12月+ 1并且在枚举中没有相应的命名值。如果您选择允许此操作,则必须假设枚举的实例可能超出范围。如果您在递增之前选择检查orig == December
,则可以将值包装回1月并消除此问题。然而,然而,你已经丢失了你已经转入新的一年的信息。
TODO部分的实施(或缺乏)将在很大程度上取决于您的个人用例。
答案 1 :(得分:13)
是的。可以对所有用户定义的类型执行运算符重载。这包括枚举。