2016-04-08 40 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