首页 > 代码库 > C++Enumerated types枚举变量

C++Enumerated types枚举变量

What?

枚举变量就是我们自己定义的变量,除了int,char,double之外,我们肯定有自己想定义的变量,eg,我们想把Monday-Sunday每一天定义为Day,Day是一个变量,我们要根据不同的Day来输出不一样的东西。

eg.

(1)define a enumerated type:

enum Day{MONDAT, TUESDAY,WEDNESDAY, THURSDAY, FRIDAY, SARTURDAY, SUNDAY};

注意:type->Day 第一个字母必须是capitalized

    value->MONDAY这些,都必须用uppercase。

注意:当声明以上时,MONDAY到SUNDAY依次会被系统赋值为0到6,如果我们要人为给不同的day赋不同的值,我们可以用:

enum Day{MONDAT=1, TUESDAY,WEDNESDAY, THURSDAY, FRIDAY, SARTURDAY, SUNDAY}:这样就会变成1到7;

enum Day{MONDAT=1, TUESDAY,WEDNESDAY, THURSDAY=30, FRIDAY, SARTURDAY, SUNDAY}:这样子就会变成1,2,3,30,31,32,33

(2)usage

Day day = MONDAY; 

int i=SUNDAY; //i就会被赋予SUNDAY的int值,例如:7

(3)usage2

enum Day{MONDAT=1, TUESDAY,WEDNESDAY, THURSDAY, FRIDAY, SARTURDAY, SUNDAY} day;

cout<<"Enter a day(1 for Monday, 2 for Tuesday....)"<<endl

int daynumber;

cin>>daynumber;

switch(daynumber)

{

  case MONDAT: cout<<"play soccer"<<endl;break;

  case TUESDAY: cout<<"play soccer"<<endl;break;

  case WEDNESDAY: cout<<"play soccer"<<endl;break;

  default: cout<<"play soccer"<<endl;

}