Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ Function to return an enum?

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

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?

like image 801
Andy Avatar asked Apr 20 '13 09:04

Andy


People also ask

Can C function return enums?

In C, you must use enum Foo until you provide a typedef for it. And then, when you refer to BAR , you do not use Foo. BAR but just BAR . All enumeration constants share the same namespace (the “ordinary identifiers” namespace, used by functions, variables, etc).

Can you cast an enum in C?

Yes. In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C.

Is enum available in C?

We can use enum in C for flags by keeping the values of integral constants a power of 2.

What is typedef enum in C?

A typedef is a mechanism for declaring an alternative name for a type. An enumerated type is an integer type with an associated set of symbolic constants representing the valid values of that type.


3 Answers

Just return the enum by value:

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

  paddleNS::COLOUR currentColour() const { return colour; }
};
like image 76
juanchopanza Avatar answered Oct 20 '22 23:10

juanchopanza


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

like image 25
Marko Ljuboja Avatar answered Oct 20 '22 22:10

Marko Ljuboja


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

  const char* currentColour() const { 
switch(couleur)
{
 case WHITE:
   return "white";
   break;
//And so on
}
}
};
like image 2
Houssem Badri Avatar answered Oct 21 '22 00:10

Houssem Badri