C ++ Function to return an enumeration?

So, I have this namespace called paddleNS for a class called paddle, inside paddleNS I have an enumeration known as 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, what I was interested in was how I get started creating a function that will return what is currently color, and there is an easier way to return it in text form instead of value, or I’d better just use the switch to figure out What is color?

+7
source share
3 answers

Just return the enumeration by value:

 class Paddle : public Entity { // as before... paddleNS::COLOUR currentColour() const { return colour; } }; 
+13
source
 class Paddle : public Entity { // ---- const char* currentColour() const { switch(couleur) { case WHITE: return "white"; break; //And so on } } }; 
+1
source

Keep an array of strings in which the indix value in this string array matches the enumeration value used.

So, if you have:

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

Then I would define an array:

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

Then, when you have a function that returns an enumeration of this type, you can simply put it in your array and get the correct color in string format.

+1
source

All Articles