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
是的.可以对所有用户定义的类型执行运算符重载.这包括枚举.