C++枚举变量与switch
枚举类型和变量如何定义,下篇博客讲得⼗分详细:
有⼏个需要注意的点:
(1)在不进⾏强制类型转换的前提下,枚举量只能由枚举类型赋值。但是,可以把枚举量赋给其它类型(枚举量被强制转换为整型)。(2)枚举量没有赋初值的话,会⾃动从0开始,按从⼩到⼤的顺序,以整数的形式初始化。
enum enumType {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
Monday~Sunday 会默认为0~6。将其中某个赋初值的话,下⼀个枚举量也会⾃动向上递增。
(3)枚举类型常和switch分⽀搭配使⽤。
⾃⼰简单练习了⼀下。⽤户输⼊0-5的数字来选择⼯作⽇,输出当天的安排。
#include<iostream>
using namespace std;
typedef enum workday
{
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
};
void chooseday(workday tempday);
int main()
{
int today;
cin >> today;
chooseday(workday(today));
enum类型如何使用system("pause");
}
void chooseday(workday tempday)
{
switch (tempday)
{
case Sunday:
{
cout << "Work,and go shopping." << endl;
break;
}
case Monday:
{
cout << "Work,and read books." << endl;
break;
}
case Tuesday:
{
cout << "Travel." << endl;
break;
}
case Thursday:
{
cout << "Work,and visit friends." << endl;
break;
}
case Friday:
{
cout << "Have a party." << endl;
break;
}
default:
cout << "Wrong input!" << endl;  break;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。