I do not understand one of the fields in the struct?

closed account (yR9wb7Xj)
Can someone explain what is going on inside the struct function? I'm really confuse why MonsterType Type; is written likes this? It's not declare anything I don't think. This solution is not mine it's a solution from another site that I found, I'm trying to understand what is going on in the code.None of these are not my comments either it came with the solution the only one that is mine is the one I'm asking a question on that has the two brackets. Thanks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
 
// Define our different monster types as an enum
enum class MonsterType
{
	OGRE,
	DRAGON,
	ORC,
	GIANT_SPIDER,
	SLIME
};
 
// Our monster struct represents a single monster
struct Monster
{

	MonsterType type;      // {{<---- What is the line of code doing? }}
	std::string name;
	int health;
};
 
// Return the name of the monster's type as a string
// Since this could be used elsewhere, it's better to make this its own function
std::string getMonsterTypeString(Monster monster)
{
	if (monster.type == MonsterType::OGRE)
		return "Ogre";
	if (monster.type == MonsterType::DRAGON)
		return "Dragon";
	if (monster.type == MonsterType::ORC)
		return "Orc";
	if (monster.type == MonsterType::GIANT_SPIDER)
		return "Giant Spider";
	if (monster.type == MonsterType::SLIME)
		return "Slime";
 
	return "Unknown";
}
 
// Print our monster's stats
void printMonster(Monster monster)
{
	std::cout << "This " << getMonsterTypeString(monster);
	std::cout << " is named " << monster.name << " and has " << monster.health << " health.\n";
}
 
int main()
{
	Monster ogre = { MonsterType::OGRE, "Torg", 145 };
	Monster slime = { MonsterType::SLIME, "Blurp", 23 };
 
	printMonster(ogre);
	printMonster(slime);
 
	return 0;

Last edited on
closed account (E0p9LyTq)
MonsterType is a user-defined enumerated constant.

1
2
3
4
5
6
7
8
9
// Define our different monster types as an enum
enum class MonsterType
{
	OGRE,
	DRAGON,
	ORC,
	GIANT_SPIDER,
	SLIME
};


So you can know what type of monster you create by a name such as OGRE instead of by a "magic" hard-coded number.

closed account (yR9wb7Xj)
Okay so are you saying in this line of code MonsterType type; inside the struct, what it's doing it's passing the enum class called MonsterType into the field of the structure that is declare to the variable type? Right?
closed account (E0p9LyTq)
An explanation of enums (bottom of the page):

http://www.cplusplus.com/doc/tutorial/other_data_types/
Topic archived. No new replies allowed.