enum枚举入门

enum 枚举类型

当一种变量的可能取值非常有限时,可以用 enum 获得直观的效果,如###1。。

在软件设计的最初阶段(概念设计),为避免过多纠缠语言的技术细节,需要用最直观的表述方式来描述问题空间,伪代码就是一个良好的运用。enum并不在该阶段使用,但可以达到类似的目的,即使思维直接作用于问题,而非电脑或者说程序语言。

enum [tag] {enum-list} [declarator];   // for definition of enumerated type

enum Day {Saturday, Sunday = 0, Monday, Tuesday, Wednesday, Thursday, Friday}; //Saturday = 0 by default, Sunday = 0 as well
void Prnt (Day day)  // Print whether a day is a 'Weekend' or a "Weekday".
{
 if (day ==0) cout << "Weekend" << endl;
 else cout << "Weekday" << endl;
}
int main (void)
{
 enum Fruit {apple, pear, orange, banana} frt1; // 'frt1' can be declarated here.

 // int apple; // error: redefinition of 'apple'

 typedef enum Fruit ShuiGuo; // In c++, 'enum' can be omitted.

 enum Fruit frt2 = apple; // In c++, 'enum' can be omitted.
 ShuiGuo frt3 = pear; // After type-declaration synonym, 'enum' can not exist here!
 
 frt1 = (Fruit) 0; // 'frt1' can be assigned with number by explicit cast.

 for (int i = apple; i <= banana; i++) ###1
  switch (i)
  {
   case apple: cout << "apple" << endl; break;
   case pear: cout << "pear" << endl; break;
   case orange: cout << "orange" << endl; break;
   case banana: cout << "banana" << endl; break;
   default: break;
  }

 // Print whether a day is a 'Weekend' or a "Weekday".
 Prnt (Saturday);
 Prnt (Sunday);
 Prnt (Monday);
 Prnt (Tuesday);
 Prnt (Wednesday);
 Prnt (Thursday);
 Prnt (Friday);

 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值