Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define an enumeration inside a class and use it from the outside

Just because I don't know exactly where to look this up in my c++ book, or on google. How do I actually define some enumerations(in this case { left=1, right=2, top=3, bottom=4 }) inside a class. I want to be able to pass this enumeration as a parameter to member functions instead of an integer, therefore using the enumeration externally...

Is there a way I can do this, or is there a better way I which I can make the enumeration specific to that class only?

Here's the code that's not working, saying enum mySprite::<unamed> myySprite::side member mySprite "mySprite::side" is not a type name for some reason:

class mySprite : public sf::Sprite
{
public:
    enum{left=1, right=2, top=3, bottom=4} side;

    float GetSide(side aSide){
        switch(aSide){
            // do stuff
        }
    };
};
like image 599
Griffin Avatar asked Jun 18 '11 21:06

Griffin


1 Answers

The simplest change needed to get your code to work is this:

class mySprite : public sf::Sprite
{
public:
    enum side{ left=1, right=2, top=3, bottom=4 };

    float GetSide(side aSide)
    {
        switch(aSide)
        {
            // do stuff
            // add breaks; as appropriate
            case left:
            case right:
            case top:
            case bottom:
        }
    }
};

You can also do it this way:

    typedef enum {left = 1, right, top, bottom} side;

Which means define an anonymous enum type for your mySprite class and make side an alias effectively accomplishing the same thing as the code above. For terseness only the first enum value needs to be assigned a starting integer. All values that come after that point are understood to be incremented by 1 each time unless you explicitly assign it something else.

like image 150
greatwolf Avatar answered Oct 05 '22 23:10

greatwolf