Win loop errors

Started by
10 comments, last by ccuccherini 7 years, 8 months ago


enum class Winner {Nobody, PlayerOne, PlayerTwo};
Winner winner = Winner::Nobody;
As soon as I get a good understanding of classes I will be switching over to what you suggest.


Heheh, sorry for the confusion. This is an enum, not a class. :)

The C++ design committee have an annoying tendency to reuse the same keywords ('class', 'static', 'struct', 'auto', etc...) for multiple different unrelated features. :rolleyes:

In this case, saying 'enum class MyEnum { };' has absolutely nothing to do with regular "classes" like:


class MyClass //Completely unrelated
{
    public:
    void DoSomething();
};


Basically, enums work like this:


enum ENUM_NAME { ONE, OR, MORE, CONSTANTS  };


For example:


//Each name within the brackets basically becomes a constant variable (there's a few differences though).
enum VehicleType { Horse, Car, Truck, Train, GiantEagle, Airplane};
 
VehicleType myType = Truck;
int myTypeAsInt = Car;


The problem with that 'regular' kind of enum is that (A) the names of the enum constants can accidentally conflict with other variable types (unless you protect them in a namespace or within a class or function's scope), and also (B) the enums automatically convert into integers if assigned to an integer, which is good in some cases (when used as what's called "bitwise flags" - you'll learn about those later), but can occasionally be a source of bugs.

By saying 'enum class' instead of just 'enum', you create what's called "strongly-typed" enums - enums that don't automatically convert to ints. As an added bonus, they are automatically in their own namespace.


enum class VehicleType { Horse, Car, Truck, Train, GiantEagle, Airplane};
 
VehicleType myType = VehicleType::Truck;
//int myTypeAsInt = VehicleType::Car; <--- Won't compile
Advertisement
SotL - Thank you for clearing that up. That's almost as bad as the English language where you can say "boot" and have it mean several different things that have nothing to do with one another.

I had seen enum used before in a tutorial I had watched before and it wasn't really explained what it was used for past the fact that that particular program would be using it to store directions (up, down, right, left, etc) so your explication is very helpful and now it makes sense why it was used in that tutorial.

This topic is closed to new replies.

Advertisement