如何在类内部定义枚举并从外部使用它
只是因为我不知道在我的 C++ 书中或在 google 上到底在哪里查找它。我如何在类中实际定义一些枚举(在本例中为 { left=1, right=2, top=3, Bottom=4 }
)。我希望能够将此枚举作为参数传递给成员函数而不是整数,因此在外部使用枚举...
有没有办法可以做到这一点,或者有没有更好的方法可以仅使枚举特定于该类?
这是不起作用的代码,表示 enum mySprite::
:
class mySprite : public sf::Sprite
{
public:
enum{left=1, right=2, top=3, bottom=4} side;
float GetSide(side aSide){
switch(aSide){
// do stuff
}
};
};
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
}
};
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
让您的代码正常工作所需的最简单的更改是这样的:
您也可以这样做:
这意味着为您的
mySprite
类定义一个匿名枚举类型,并将side
设为别名有效地完成与上面的代码相同的事情。为了简洁起见,只需为第一个枚举值分配一个起始整数。该点之后的所有值都被理解为每次递增 1,除非您显式为其分配其他值。The simplest change needed to get your code to work is this:
You can also do it this way:
Which means define an anonymous enum type for your
mySprite
class and makeside
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.我认为这个例子已经说明了一切:
I think this example explains it all:
您需要将其定义为一种类型,以便在类外部使用它和/或对参数进行强类型化。否则它被简单地定义为
int
,它的访问修饰符也必须是 public: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: