Enum help

Started by
3 comments, last by Saruman 11 years, 5 months ago
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.
Advertisement
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.
thank you
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)
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.

This topic is closed to new replies.

Advertisement