Section 15.8 Values for Enums
In general, you should not need to care about what numeric values each enum option represents.Although you can use a static cast to get or set the value, you would never want to say
static_cast<Suit>(1)
instead of
Suit::DIAMONDS
.
However, there are times when the enumerated values naturally map to integers. For example, if we are using the enumerated type to represent the rank of playing cards, it might be useful to have
Rank::ACE
have the value 1,
Rank::TWO
have the value 2,
Rank::JACK
have the value 11, etc.... That way we can take any rank and do a
static_cast<int>
to get its value.
In this case, we want the lowest value used to be 1, not 0. We can do this by explicitly setting the value of the first item in the enum to 1. The rest of the values will be set automatically based on that first value. For example, if we want
ACE
to be 1, we can write:
enum class Rank {
ACE = 1, TWO, THREE, FOUR, FIVE,
SIX, SEVEN, EIGHT, NINE, TEN,
JACK, QUEEN, KING
};
Now
ACE
is 1,
TWO
is 2, and so on. The last value,
KING
, will be 13.
We can even assign values to other items in the list. Say we want to represent US coin types. We could write:
enum class Coin {
PENNY = 1, NICKEL = 5, DIME = 10, QUARTER = 25
};
Now we can use the enumerated type to represent the value of a coin. For example, if we want to represent a quarter, we can write:
Coin myCoin = Coin::QUARTER;
And if we want to get the value of that coin, we can write:
int value = static_cast<int>(myCoin);
And the value of
value
will be 25.
There are some significant limitations to this technique. Every option needs a different value - you could not have
Rank::JACK
,
Rank::QUEEN
,
Rank::KING
all have the value 10 if you were programming a game where all of those cards should have the same value.
Given this limitation, and the fact that
getValue(myCoin)
is much clearer to read than
static_cast<int>(myCoin)
, it is likely better to use a function to turn enumerated options into the value we want them to represent. This function will give the correct value for each coin type, regardless of whether or not the enum was defined with specific numeric values:
int getValue(Coin c) {
switch (c) {
case Coin::PENNY: return 1;
case Coin::NICKEL: return 5;
case Coin::DIME: return 10;
case Coin::QUARTER: return 25;
}
}
Checkpoint 15.8.1.
Construct a
Class
enum and a Student struct with a string name and Class classStanding. Put the enum before the struct:
enum class Class {
---
struct Class { #paired
---
FRESHMEN = 9,
---
SOPHOMORE,
---
JUNIOR,
---
SENIOR
};
---
struct Student {
---
enum class Student { #paired
---
std::string name;
---
Class classStanding;
---
Class::classStanding; #paired
---
};
You have attempted
of
activities on this page.