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

在进行C++编程时,遇到枚举类型在循环中的使用出现异常。本文探讨了枚举在循环中的常见问题,包括枚举的定义、枚举与循环的交互以及可能导致的问题和解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值