C++里枚举在循环里的问题

来源:互联网 发布:麦星投资 知乎 编辑:程序博客网 时间:2024/06/05 18:34

在测试枚举功能时遇到以下问题。

#include <iostream>
using namespace std;
enum gameresult
{
 win,lose,tie,cancel
};
int main()
{
 gameresult result;
 for(gameresult count = win;count <= cancel; count++)
 {
  result = gameresult(count);
  if(result == win)
  cout<<"the game was win!"<<endl;
  if(result == lose)
  cout<<"the game was lose."<<endl;
  if(result == tie)
  cout<<"the game was played"<<endl;
  if(result == cancel)
  cout<<"the game was cancelled!"<<endl;
 }
 getchar();
 return 0;
}

调试结果为:error C2676: 二进制“++”:“gameresult”不定义该运算符或到预定义运算符可接收的类型的转换
分析原因为:gameresult是指针变量,只能赋值不能运算。后面改成了int定义count就好了,然后把count作为数组下坐标一样使用,调试就成功了。

下面是正确代码:
#include <iostream>
using namespace std;
enum gameresult
{
 win,lose,tie,cancel
};
int main()
{
 gameresult result;
 for(int count = win;count <= cancel; count++)
 {
  result = gameresult(count);
  if(result == win)
  cout<<"the game was win!"<<endl;
  if(result == lose)
  cout<<"the game was lose."<<endl;
  if(result == tie)
  cout<<"the game was played"<<endl;
  if(result == cancel)
  cout<<"the game was cancelled!"<<endl;
 }
 
 return 0;
}

原创粉丝点击