Coming from a C# background from a night course at a local college, I've sort of started my way in C++. Having a lot pain getting used to the syntax. I'm also still very green when it comes to coding techniques.
From my WinMain
function, I want to be able to access a variable which is using an enum I declared in another class.
(inside core.h) class Core { public: enum GAME_MODE { INIT, MENUS, GAMEPLAY }; GAME_MODE gameMode; Core(); ~Core(); ...OtherFunctions(); }; (inside main.cpp) Core core; int WINAPI WinMain(...) { ... startup code here... core.gameMode = Core.GAME_MODE.INIT; ...etc... }
Basically I want to set that gameMode to the enum value of Init
or something like that from my WinMain
function. I want to also be able to read it from other areas.
I get the error...
expected primary-expression before '.' token
If I try to use core.gameMode = Core::GAME_MODE.INIT;
, then I get the same error.
I'm not fussed about best practices, as I'm just trying to get the basic understanding of passing around variables in C++ between files. I'll be making sure variables are protected and neatly tucked away later on once I am use to the flexibility of the syntax.
If I remember correctly, C# allowed me to use Enums from other classes, and all I had to do was something like Core.ENUMNAME.ENUMVALUE
.
I hope what I'm wanting to do is clear :\ As I have no idea what a lot of the correct terminology is.
You have to put the enum in a header file, and use #include to include it in the source file.
I declare enums (or whatever for that matter) inside class in private section, only if it is internally needed by the class itself. In all other cases, I prefer to define it outside, especially in C++11, because if you declare this inside class, you wouldn't be able to use it in lambda.
You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: “permanent”, “temp”, “apprentice”), or flags (“execute now”, “defer execution”).
There is no inheritance with enums. You can instead use classes with named const ints. Show activity on this post.
Use
core.gameMode = Core::INIT;
The individual values of an enumeration are scoped not within that enumeration but at the same level as the enumeration itself. This is something that most other languages (including C#) do differently, and C++0x will allow both variants so that there,
core.gameMode = Core::GAME_MODE::INIT;
will also be legal.
In addition, the strongly typed enums that will be added in C++0x (enum class
) will put the enum values only within the scope of the enum (i.e. as in C#); this solves the problem you noted in your comment that for "normal" enums, the identifiers for enum values need to be unique across all enums defined in the same scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With