繁体   English   中英

C ++枚举到字符串切换不起作用

[英]C++ Enum to String Switch Not Working

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

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 =“ 3”,color_string =“ green”,shading_string =“ outlined”和shape_string =“ diamond”。

您需要对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;
}

您的开关盒不正确。 您需要在每种情况下都稍作break ,否则解决方案将进入每种情况,直到完成为止,并且在遇到所需情况时也不会中断。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM