
枚举类型,在C++中本质是整型数值,即int类型。
枚举名只是给程序的编写和维护者阅读的。
比如枚举
enum test{
TEST0,
TEST1,
TEST2
}
中,TEST0, TEST1和TEST2的值就是0,1,2。
所以对于枚举变量,其输入输出也可以按照int类型进行输入输出。
如
enum test t
cin >>t//输入
cout <<"get a enum t, value is "<<t<<endl//输出
一、对枚举型的变量赋值。
实例将枚举类型的赋值与基本数据类型的赋值进行了对比:
方法1:先声明变量,再对变量赋值
#include<stdio.h>/* 定义枚举类型 */
enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN }
void main()
{
/* 使用基本数据类型声明变量,然后对变量赋值 */
int x, y, z
x = 10
y = 20
z = 30
/* 使用枚举类型声明变量,再对枚举型变量赋值 */
enum DAY yesterday, today, tomorrow
yesterday = MON
today = TUE
tomorrow = WED
printf("%d %d %d \n", yesterday, today, tomorrow)
}
方法2:声明变量的同时赋初值
#include <stdio.h>/* 定义枚举类型 */
enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN }
void main()
{
/* 使用基本数据类型声明变量同时对变量赋初值 */
int x=10, y=20, z=30
/* 使用枚举类型声明变量同时对枚举型变量赋初值 */
enum DAY yesterday = MON,
today = TUE,
tomorrow = WED
printf("%d %d %d \n", yesterday, today, tomorrow)
}
方法3:定义类型的同时声明变量,然后对变量赋值。
#include <stdio.h>/* 定义枚举类型,同时声明该类型的三个变量,它们都为全局变量 */
enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN } yesterday, today, tomorrow
/* 定义三个具有基本数据类型的变量,它们都为全局变量 */
int x, y, z
void main()
{
/* 对基本数据类型的变量赋值 */
x = 10 y = 20 z = 30
/* 对枚举型的变量赋值 */
yesterday = MON
today = TUE
tomorrow = WED
printf("%d %d %d \n", x, y, z) //输出:10 20 30
printf("%d %d %d \n", yesterday, today, tomorrow) //输出:1 2 3
}
方法4:类型定义,变量声明,赋初值同时进行。
#include <stdio.h>/* 定义枚举类型,同时声明该类型的三个变量,并赋初值。它们都为全局变量 */
enum DAY
{
MON=1,
TUE,
WED,
THU,
FRI,
SAT,
SUN
}
yesterday = MON, today = TUE, tomorrow = WED
/* 定义三个具有基本数据类型的变量,并赋初值。它们都为全局变量 */
int x = 10, y = 20, z = 30
void main()
{
printf("%d %d %d \n", x, y, z) //输出:10 20 30
printf("%d %d %d \n", yesterday, today, tomorrow) //输出:1 2 3
}
2、对枚举型的变量赋整数值时,需要进行类型转换。
#include <stdio.h>enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN }
void main()
{
enum DAY yesterday, today, tomorrow
yesterday = TUE
today = (enum DAY) (yesterday + 1) //类型转换
tomorrow = (enum DAY) 30 //类型转换
//tomorrow = 3 //错误
printf("%d %d %d \n", yesterday, today, tomorrow) //输出:2 3 30
}
3、使用枚举型变量
#include<stdio.h>enum
{
BELL = '\a',
BACKSPACE = '\b',
HTAB = '\t',
RETURN = '\r',
NEWLINE = '\n',
VTAB = '\v',
SPACE = ' '
}
enum BOOLEAN { FALSE = 0, TRUE } match_flag
void main()
{
int index = 0
int count_of_letter = 0
int count_of_space = 0
char str[] = "I'm Ely efod"
match_flag = FALSE
for( str[index] != '\0' index++)
if( SPACE != str[index] )
count_of_letter++
else
{
match_flag = (enum BOOLEAN) 1
count_of_space++
}
printf("%s %d times %c", match_flag ? "match" : "not match", count_of_space, NEWLINE)
printf("count of letters: %d %c%c", count_of_letter, NEWLINE, RETURN)
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)