C++ 函数返回一个枚举?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16118785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:05:16  来源:igfitidea点击:

c++ Function to return an enum?

c++functionenums

提问by Andy

So I have this namespace called paddleNS for the class called paddle, inside paddleNS I have an enum known as colour

所以我有一个名为 paddleNS 的命名空间,用于名为 paddle 的类,在 paddleNS 内部我有一个名为 color 的枚举

namespace paddleNS
{
   enum COLOUR {WHITE = 0, RED = 1, PURPLE = 2, BLUE = 3, GREEN = 4, YELLOW = 5, ORANGE = 6};
}

class Paddle : public Entity
{
private:
    paddleNS::COLOUR colour;
public:
    void NextColour();
    void PreviousColour();
    void PaddleColour(paddleNS::COLOUR col) { colour = col; }
};

Now then, what I was wondering is how would I go about creating a function that will return what the colour currently is also is there an easier way to return it in text form instead of a value or am I better of just using a switch to figure out what the colour is?

现在,我想知道的是我将如何创建一个函数来返回当前的颜色,是否有更简单的方法以文本形式而不是值返回它,或者我最好只使用 switch弄清楚颜色是什么?

回答by juanchopanza

Just return the enum by value:

只需按值返回枚举:

class Paddle : public Entity
{
  // as before...

  paddleNS::COLOUR currentColour() const { return colour; }
};

回答by Houssem Badri

class Paddle : public Entity
{
  // ----

  const char* currentColour() const { 
switch(couleur)
{
 case WHITE:
   return "white";
   break;
//And so on
}
}
};

回答by aaron burns

Keep an array of strings where the indix in to this array of strings matches the enum value you are using.

保留一个字符串数组,其中该字符串数组中的索引与您正在使用的枚举值匹配。

So if you have:

所以如果你有:

enum COLOUR {WHITE = 0, RED = 1, PURPLE = 2, BLUE = 3, GREEN = 4, YELLOW = 5, ORANGE = 6};

I would then have an array defined:

然后我会定义一个数组:

String colors[] = {white, red, purple, blue, green, yellow, orange}

Then when you have a function return an enum of this type you can just put it into your array and get the correct color in string format.

然后当你有一个函数返回一个这种类型的枚举时,你可以将它放入你的数组中并以字符串格式获取正确的颜色。

回答by Marko Ljuboja

Hey you can make your function in header that look like this:

嘿,您可以在标题中使您的函数看起来像这样:

enum COLOUR function();

and when you define a function:

当你定义一个函数时:

enum Paddle::COLOUR Paddle::function(){
        // return some variable that hold enum of COLOUR
}

in main.cpp i enter code herethink you can manage it

在 main.cpp 我enter code here认为你可以管理它