枚举变量能否作为循环控制变量?

图片说明

我在书上看到有把枚举变量当做循环控制变量的,但我在用的时候总是报错,是在vc++6.0中不支持这样做吗,我从网上找的程序也无法正常运行,报错为:E:\CYUYAN\练习\枚举_1.cpp(27) : error C2676: binary '++' : 'enum main::season' does not define this operator or a conversion to a type acceptable to the predefined operator

#include<stdio.h>

void main()
{ 
    enum season {spring=1,summer,autumn,winter}s;

    for(s=spring; s<=winter; s++)
        printf("%d\n",s);
}

你这个错是枚举型没有++操作,可以修改为s=s+1,试试

你这样用其实不是很符合枚举存在的意义,因为我们定义枚举的时候,其实想用的是他的变量名,而重点不是想用他的值,因为他的值只是一个index。
一般枚举的变量名的意思可以非常直观,比如
enum selfError{
NO_ERROR,
INVALED_PARM,
NULL_PTR,
}

这样你在使用的时候就可以非常方便地根据变量名本身含义去做逻辑处理
定义一个返回类型为selfError的函数
selfError function1() {
int err = INVALED_PARM;
。。。。。。。
return err;
}

然后引用的时候很方便地使用枚举型
int err = function1();
if (err ==NO_ERROR ){
printf("调用成功");
}

把for里面的i++改为i=(Color)(i+1)

#include<stdio.h>

void main()
{ 
    enum season {spring=1,summer,autumn,winter}s;

    for(int s=(int)spring; s<=(int)winter; s++)
        printf("%d\n",s);
}