Game Development Reference
In-Depth Information
Enums also allow us to assign a value to each element. In the Color enum we currently have Red
assigned the value 0, Green 1 and Blue 2. In the enum definition we could have used the following:
enum class Color
{
Red,
Green = 10,
Blue
};
In the preceding enum, Red is still 0, and Green is 10; however, Blue is 11, as it directly follows Green .
There are few occasions where we need to specify the values of enums as they are most useful for
creating more readable code; but it is useful to understand that this is possible because you will
come across code written by others that will use this feature.
It's also important to note that the enum class is a C++11 construct. Prior to C++11 the enum would
have been created using the following:
enum Color
{
Red,
Green,
Blue
};
C++11 style enums are known as strongly typed enums. The compiler will not allow you to
accidentally use integers in place of the enum values. It also wouldn't have been possible to use the
value Red in two different enums.
enum Color
{
Red,
Green,
Blue,
};
enum TrafficLights
{
Red,
Amber,
Green
};
This is not allowed with older enums, as the code to define a variable would look like:
Color currentColor = Red;
TrafficLights = currentLight = Red;
As you can see, we have no way of knowing which Red is to be used. This is even worse with the
Green value, as it would have a different integer representation: 1 in Color and 2 in TrafficLights .
This could cause bugs in our code as it would be valid to use the TrafficLights version of Green
 
Search WWH ::




Custom Search