【问题标题】:C++ Enum to String Switch Not WorkingC ++枚举到字符串切换不起作用
【发布时间】:2016-04-08 00:32:24
【问题描述】:

我正在用一些枚举类型实例化一个对象,并尝试根据这些枚举类型设置一些字符串成员。但是,当我在调试和单步执行时,用于设置字符串的开关会触发每种情况,并且每个字符串都会被设置为每种枚举类型的最后一种情况。

enum Number {
one,
two,
three
};

enum Color {
    purple,
    red,
    green
};

enum Shading {
    solid,
    striped,
    outlined
};

enum Shape {
    oval,
    squiggle,
    diamond
};

Card::Card(Number num, Color colour, Shading shade, Shape shaper) {
number_ = num;
color_ = colour;
shading_ = shade;
shape_ = shaper;
setStrings();
}

void Card::setStrings() {
switch (number_) {
case one:
    number_string = "one";
case two:
    number_string = "two";
case three:
    number_string = "three";
}
switch(color_) {
case purple:
    color_string = "purple";
case red:
    color_string = "red";
case green:
    color_string = "green";
}
switch (shading_) {
case solid:
    shading_string = "solid";
case striped:
    shading_string = "striped";
case outlined:
    shading_string = "outlined";
}
switch (shape_) {
case oval:
    shape_string = "oval";
case squiggle:
    shape_string = "squiggle";
case diamond:
    shape_string = "diamond";
}

}

我使用重载构造函数实例化的每张卡片都有 number_string = "three"、color_string = "green"、shading_string = "outlined" 和 shape_string = "diamond"。

【问题讨论】:

    标签: c++ visual-studio visual-c++ enums switch-statement


    【解决方案1】:

    你需要对 switch 语句的 case 子句使用 break,否则它会失败。这是一个示例和详细信息。 https://10hash.com/c/cf/#idm45440468325552

    #include <stdio.h>
    
    int main()
    {
      int i  = 65;
    
      switch(i)
      {
        case 'A':
          printf("Value of i is 'A'.\n");
          break;
        case 'B':
          printf("Value of i is 'B'.\n");
          break;
        default:
          break;
      }
    
      return 0;
    }
    

    【讨论】:

    • 这永远不会失败,但我需要休息
    • 如果你不使用休息,它总是会失败。
    【解决方案2】:

    您的开关盒不正确。您需要在每个案例之后为您的解决方案添加一个break,否则它将进入每个案例直到完成,并且在遇到您想要的案例时不会中断。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多