In terms of having to type Card::Rank::TEN
according to one of the answers here you should be able to use Card::TEN
instead, provided you declare your enum
like this:
class Card
{
public:
enum Rank { TWO = 2, THREE = 3, FOUR = 4, FIVE = 5, SIX = 6, SEVEN = 7,
EIGHT = 8, NINE = 9, TEN = 10, JACK = 10,
QUEEN = 10, KING = 10, ACE = 11 };
You can't use two of the same values in a switch
statement no matter what. This is because when the code runs and you get a value 10
your code will not be able to determine if it is a Ten, Jack, Queen or a King.
Either change the values or use only one of them in your switch. Here is a contrived example:
int function(int value)
{
int rv = 0;
switch (value)
{
case 0:
rv = 7;
break;
case 1:
rv = 8;
break;
case 1:
rv = 21;
break;
default:
rv = 0;
break;
}
return rv;
}
int main()
{
printf("What does function(1) return? %d", function(1));
return 0;
}
This would not make sense since we return two different values when we are passed the value 1
so the compiler does not allow it.
It is the same if you use your enum
values of Card::Rank::TEN
in the switch because their value is the same the compiler doesn't allow it.
Card::Rank card = Card::Rank::TEN;
switch(card)
{
// Some cases...
case Card::Rank::JACK:
// Do something
break;
case Card::Rank::TEN: // <- not allowed since it is the same as the case for Card::Rank::JACK.
// Do something else
break;
// Some more cases...
}
This isn't allowed. The following would seem like it should be ok since the compiler should be able to see that it is the same code being run for both cases but it still won't work.
switch(card)
{
// Some cases...
case Card::Rank::JACK:
case Card::Rank::TEN: // <- still not allowed, even though both code paths for case 10 do the same thing...
// Do something else
break;
// Some more cases...
}
and I'm sorry but I can't give good reasoning for this other than, it is probably not allowed in the standard itself for consistency. Someone else might be able to elaborate on this.