c/c++ enum枚举用法

1:用法

enum <类型名> {<枚举常量表>};
比如:
enum weekday {Mon, Tue,……Sun};
enum自动从0开始为枚举元素赋值:
Mon = 0;
Tue = 1;
.
.
.
Sun = 6;
如果我们不想从0开始,可以:
enum weekday {Mon = 1, Tue,……Sun};
这样:
Mon = 1;
Tue = 2;
.
.
.
Sun = 7;
(这其实体现了枚举的好处有关我们有define的话
#define Mon 1
#define Tue 2
#define Wed 3
#define Thu 4
#define Fri 5
#define Sat 6
#define Sun 7
而用enum的话比较简洁)
定义枚举变量
enum set_color1{red……}color1, color2;
枚举变量可以这样赋值;
color1 = red;
color2 = color1;
不可以直接color1 = 1;//非法
但是可以强制类型转换
color1 = set_color1(1);
enum set_color2{red……};
set_color1 color3, color4;

2:注意

枚举变量可以直接输出,但不能直接输入。
不能直接将常量赋给枚举变量。
不同类型的枚举变量之间不能相互赋值。

实例

在这里插入图片描述

#include <iostream>

using namespace std;

enum CPU_Rank{i3 = 2, i5, i7};
enum set_color{Red, Blue, Yellow}color1;

int main()
{
	CPU_Rank computer1, computer2, computer3;
	computer1 = i3;   
	computer2 = i5;   
	computer3 = i7;    
	
	
	cout << computer1 << endl << computer2 << endl << computer3 << endl; //修改i3前, computer1为0, computer2为1, computer为2 
	//修改i3 = 2;
	computer2 = i5;
	cout << computer2 << endl;  //computer2为3 
	color1 = set_color(1);
	cout << color1 << endl;
	// computer1 = 2; 
	//不能直接将常量赋给枚举变量
	//  cin >> computer1; 
	//枚举变量可以直接输出但不能直接输入 
	
	return 0;	
} 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值