how to define an enumeration inside a class and us

2019-06-20 04:05发布

问题:

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
        }
    };
};

回答1:

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.



回答2:

I think this example explains it all:

class A {
public:
    enum directions { top, left, right, bottom }; // directions is the type
                                                  // of the enum elements

    void f(directions dir) {
        if (dir == left) {
            // ...
        } else {
            // ...
        }
    }
};

A object;
object.f(A::top);


回答3:

You need to define it as a type to use it outside the class and/or strongly-type the parameter. Otherwise it is simply defined as an int, its access modifier must also be public:

 
class foo {
public:
    typedef enum DIRECTION {
        LEFT = 1,
        RIGHT,
        TOP,
        BOTTOM,
    };
    void SetDirection(foo::DIRECTION dir) {
        _direction = dir;
    }
    //...
protected:
    //...
private:
    foo::DIRECTION _direction;
    //...
};

int main() {
    //...
    foo bar;
    bar.SetDirection(foo::BOTTOM);
    //...
}