簡體   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