Enumerations: enum class
Some values can only be one of a few options. A game is in one state at a time: the hero is exploring, or fighting, or the game is over. You could keep the state in a string, std::string state = "fighting";, but a typo such as state == "figthing" compiles without an error, and the condition is simply never true. A number, int state = 1;, is no better: what does 1 mean?
An enumeration is a type with a fixed set of values, which you list yourself:
enum class State { Exploring, Fighting, GameOver };The keywords enum class create the type State, and the braces hold all the values it can have. As with a struct, the definition goes above main and ends with a semicolon. You write a value with the type's name and two colons in front, State::Fighting, and you compare values with == and !=:
#include <iostream>
enum class State { Exploring, Fighting, GameOver };
int main() {
State state = State::Exploring;
std::cout << "The hero sees a goblin." << std::endl;
state = State::Fighting;
if (state == State::Fighting) {
std::cout << "Fight!" << std::endl;
}
return 0;
}This prints:
The hero sees a goblin.
Fight!Now a typo is an error that the compiler finds. For State::Figthing, it even suggests what you meant: no member named 'Figthing' in 'State'; did you mean 'Fighting'? Without State::, a plain Fighting ends with use of undeclared identifier 'Fighting'.
An enumeration's value can't be printed. std::cout << state ends with the same long error as printing a struct:
main.cpp:11:19: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'State')To show it, write a function that turns it into a string:
std::string stateName(State state) {
if (state == State::Exploring) {
return "exploring";
} else if (state == State::Fighting) {
return "fighting";
}
return "game over";
}An enumeration is a small value, so pass it to functions by value, like an int. It can also be a member of a struct: in the task, each item in a shop has its rarity.
Instructions
- 1
The items in the shop have a rarity, but the type
Raritydoesn't exist yet. In place of the first comment, define the enumerationRaritywith the valuesCommon,RareandLegendary. The program then prints the items with their prices. - 2
In place of the second comment, write a function
std::string rarityName(Rarity rarity)that returnscommon,rareorlegendary. Use it in the loop, so that each line ends with the item's rarity:Wooden Shield: 20 gold, common. Keep the lines of the vector as they are: the exercise will also try other rarities. - 3
The merchant buys only rare and legendary items. Below the loop, add up the prices of all the items that aren't common, and print the sum once:
Worth selling: 1050 gold.