Sign in to follow this  

Enum help

This topic is 1905 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello,

i am working with enumerators and i was wondering how i would (if i can) use an enum as a parameter for the constructor of a class, and then make an instance of a class with one of the values i used in the enum as a parameter. I probably didn't explain it properly but here is and example:

class Item{
public:
enum Type{WEAPON, ARMOR, CONSUMABLE, TRASH};
Item(string name, Type type, int rarity, int value);
...
};

int main(){

Item sword ("SWORD", WEAPON, 10, 1000);
...

return 0;
}

Where is says WEAPON, that is one of the enum values. This is my problem, it has a red line under it and says "Identifier "WEAPON" is undefined". I dont really know that much about enum, the book i'm using just briefly touches on them, but im not sure if i call it like a member function, or i cannot do it at all.

So i am making a text game because i realized i didn't know C++ well enough to move onto using SDL. I am trying to use as many of C++'s functionalists in this game so i ca learn as much as possible with this project. All comments are appreciated.

Share this post


Link to post
Share on other sites
If you define the enum inside a class, outside the class you need to prefix enum values with the class name. In this case you can use Item::WEAPON.

Share this post


Link to post
Share on other sites
To explain further, anything outside of your class doesn't know the Type enum exists. Your Item class knows it exists, but that knowledge is contained inside the class, since you declared the enum inside the class. So, if you want anything else to use the Type enum, you have to tell them where to look.
The :: operator refers to the contents of the Item class itself, not any specific Item instance, so you use it to refer to the Item::Type enum. You'd also use it to refer to static members, the contents of namespaces (since namespaces can't have instances) and probably more, but I'm a C++ newb myself. :) (Just not a coding newb)

Share this post


Link to post
Share on other sites
Also note that if you are able to use C++11 you can do the following:

[source lang="cpp"]enum class ItemType
{
Weapon,
Armor,
Consumable,
Trash
};[/source]Which gives you a type safe enum.

Share this post


Link to post
Share on other sites

This topic is 1905 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this