C++枚举变量与switch

枚举类型和变量如何定义,下篇博客讲得十分详细:

https://blog.csdn.net/bruce_0712/article/details/54984371

 

有几个需要注意的点:

(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));

	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;
	}
}

  

posted @ 2019-07-29 21:12  MorpheusDong  阅读(5844)  评论(0编辑  收藏  举报