C/C++日志18

enum 是 C 和 C++ 中的一个关键字,用于定义枚举类型(enumeration)。

enum 枚举类型名称 {
    常量1 = 值1,
    常量2 = 值2,
    常量3 = 值3,
    ...
};
enum Day 
{
	  Sunday,    // 默认为 0
	  Monday,    // 默认为 1
	  Tuesday,   // 默认为 2
	  Wednesday, // 默认为 3
	  Thursday,  // 默认为 4
	  Friday,    // 默认为 5
	  Saturday   // 默认为 6
};

enum Day today = Monday;  // today = 1
enum Color 
{
    Red = 1,
    Green = 3,
    Blue = 5
};
enum Color favorite = Green;  // favorite = 3

#include<iostream>
using namespace std;
int main()
{
	enum Day
	{
		Sunday,
		Monday,
		Tuesday,
		Wednesday,
		Thursday,
		Friday,
		Saturday
	};
	enum Day today = Monday;
	// 打印枚举值(数字值)
	cout << today << endl;//输出1
	// 如果想打印枚举名称,可以使用 switch 语句
	switch (today)
	{
		case Sunday: cout << "Sunday"; break;
		case Monday: cout << "Monday"; break;
		case Tuesday: cout << "Tuesday"; break;
		case Wednesday: cout << "Wednesday"; break;
		case Thursday: cout << "Thursday"; break;
		case Friday: cout << "Friday"; break;
		case Saturday: cout << "Saturday"; break;
	}
}

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务