pdf
pdf

Reputation: 19

Error in creating a new type in c++

I just started to learn c++ and i have the following problem in this simple code:

enum class color_type {green,red,black};

color_type color(color_type::red);

I get the error "color_type is not a class or namespace". My goal is to create a variable of type color_type that can only take values red, black and green. Could you please help me? Thank you

Upvotes: 1

Views: 88

Answers (2)

David Woo
David Woo

Reputation: 791

Your code looks like valid c++11 to me.

If your compiler does not support c++11 then you simulate an enum class with a namespace or struct like so

 struct colour_type
 {
      enum value
      {
            red, 
            green,
            blue
      }
 }

 //usage is like so
 colour_type::value myColour = colour_type::red;

It's not perfect but it keeps the enum in its own scope.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

It seems that your compiler does not support qualified names of unscoped enumerators (I mean your post before its edition when there was shown an unscoped enumeration). Write simply

enum color_type {green,red,back};
color_type color(red);

Or you could use a scoped enumeration as for example

enum class color_type {green,red,back};
color_type color(color_type::red);

In fact these declarations

enum color_type {green,red,back};
color_type color(color_type::red);

are correct according to the current C++ Standard.

Upvotes: 0

Related Questions