2016-04-08 41 views
-1

我使用几个枚举类型实例化一个对象,并试图设置一些基于这些枚举类型的字符串成员。但是,当我正在调试和步骤时,用于设置字符串的开关触及每个事件,并且每个字符串都被设置为每个枚举类型的最后一种情况。C++枚举到字符串开关不工作

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 = “三国”,COLOR_STRING = “绿色”,shading_string = “概述”,并shape_string = “钻石”。

回答

1

您的开关盒不正确。您需要在每种情况下为您的解决方案放置一个break,否则它将进入每种情况,直到它完成并且在遇到您想要的情况时不会中断。

2

您需要为switch语句的case语句使用break,否则它是一个fall语句。这里有一个例子和你的细节。 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; 
} 
+0

它永远不会是一个突破,但我需要休息 –

+1

如果你不使用休息,这将永远是一个贯穿始终。 – user902384