C++中枚举类型++运算符重载

VC中不支持枚举类型的++操作。决定重载一下++运算符!

先由简单开始,重载一个枚举型的日期的例子。

 #include enum weekday{ sun=7, mon=1, tue, wed, thu, fri, sat, }; weekday& operator ++(weekday& e); main() { weekday workday1; workday1=(enum weekday)1; printf("workday1=%d/n",workday1); workday1++; printf("workday1=%d/n",workday1); return 0; } weekday&operator++(weekday &e) { int i=e; e=(enum weekday)(i+1); return e; }

然后一个是5个球中选三个的例子。

#include using namespace std; enum color_5balls{red,yellow,blue,white,black}; color_5balls& operator ++(color_5balls & e); void main() { color_5balls i,mid; color_5balls j; color_5balls k; int n=0,loop ; for(i=red;i<=black;i++) for(j=red;j<=black;j++) { if(i!=j) for(k=red;k<=black;k++) if((k!=i)&(k!=j)) { n=n+1; printf("%d",n); for(loop=1;loop<=3;loop++) { switch(loop) { case 1:mid=i;break; case 2:mid=j;break; case 3:mid=k;break; default:break; } switch(mid) { case red:printf("%-10s","red");break; case yellow:printf("%-10s","yellow");break; case blue:printf("%-10s","blue");break; case white:printf("%-10s","white");break; case black:printf("%-10s","black");break; default :break; } } printf("/n"); } } while(1); } color_5balls&operator++(color_5balls &e) { int i=e; e=(enum color_5balls)(i+1); return e; }

 他们两个的方法是一样的。如果要在类中重载的话可能要加friend 关键词。

你可能感兴趣的:(C++中枚举类型++运算符重载)