c++ 不能出现在常量表达式中|

标签 c++

<分区>

Possible Duplicate:
How do I select a range of values in a switch statement?

我遇到了一些错误,现在我已经搜索了一段时间,但我不知道错误的原因是什么。 (我对编程很陌生。)

这是我遇到的错误:

error: 'Essais' cannot appear in a constant-expression| (line 200)
warning: overflow in implicit constant conversion| (line 202)

我有箱子和床单:

  char AfficherCote (int Essais)
 {
 char Cote;
 switch (Essais)
  {
(line200)       case Essais<=20:
    {
(line 202)           Cote='Excellent';

        return (Cote);
        break;
    }
    case Essais<=40:
    {
        Cote='Très bon';
        return (Cote);
        break;
    }
    case Essais<=60:
    {
        Cote='Bon';
        return (Cote);
        break;
    }
    case Essais<=80:
    {
        Cote='Moyen';
        return (Cote);
        break;
    }
    case Essais<=100:
    {
        Cote='Muvais';
        return (Cote);
        break;
    }
    case Essais>=100:
    {
        Cote='Très mauvais';
        return (Cote);
    }
  }
}

最佳答案

switch-case仅适用于常量值(*)(例如 3'a' ),不适用于范围(例如 <=100 )。您也不得在 case 中包含变量名称陈述。正确的语法如下:

switch (Essais)
{
case 1:
   /* ... */
  break;
case 2:
   /* ... */
   break;
default:
   /* ... */
}

如果您需要范围测试,请使用 if而不是 switch-case :

if (Essais <= 80)
  return "Cote";
else if (Essais <= 100)
  return "Muvais";

另请注意,您不能使用单引号 '对于字符串。使用双引号"相反,并使用 std::string 类型的变量(不是 char )来存储字符串。


(*) 准确地说,case 中给出的条件statements 必须是整数类型、枚举类型或类类型的常量表达式可转换为整数或枚举类型(有关详细信息,请参阅 C++ 标准的 §6.4.2/2 ).

关于c++ 不能出现在常量表达式中|,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13354644/

相关文章:

c++ - 对 UTF-8 字符串进行排序?

c++ - 由于指针导致的段错误

c++ - 避免模​​板扩散

c++ - 为什么我的程序在这一行崩溃了?

c++ - 为什么我必须确定重载模板基类方法的范围?

c++ - 当右侧是临时的时,co_return 与 co_yield

c++ - 段错误并返回存储在元素中的值?

c++ - 在具有 'has-a' 关系的 C++ 类中两次调用析构函数的问题

c++ - 分形生成代码无法正常工作

c++ - 在 Rcpp 中为具有重复迭代的模型正确设置 GSL RNG 种子