如何在类中定义一个枚举并从外部使用它 [英] how to define an enumeration inside a class and use it from the outside

查看:2491
本文介绍了如何在类中定义一个枚举并从外部使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是因为我不知道在哪里查找这个在我的c ++书,或在谷歌。我如何在类中定义一些枚举(在这种情况下 {left = 1,right = 2,top = 3,bottom = 4} )。我想能够将此枚举作为参数传递给成员函数而不是整数,因此使用外部枚举...

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...

有一种方法我可以做到这一点,还是有一个更好的方法,我可以让枚举特定于该类只有

这里的代码不工作,说枚举mySprite ::< unamed> myySprite :: side member mySpritemySprite :: side不是类型名称出于某种原因:

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


推荐答案

让代码工作的最简单的改变这个:

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

您也可以这样做:

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

这意味着为 mySprite class,并使 side 有效地实现与上面的代码相同的东西。对于简洁,只有第一个枚举值需要分配一个起始整数。除非您明确指定其他值,否则所有在该点之后的值都会被加1。

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.

这篇关于如何在类中定义一个枚举并从外部使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆