1

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

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
pdf
  • 19
  • 1

2 Answers2

1

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.

David Woo
  • 749
  • 4
  • 13
0

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • I think, c++11 has a require to specify `enum class`'s scope, is not it? It does not compile also on g++ 4.9.2 with c++11 so you may be wrong and I am right :) – VP. May 30 '15 at 10:11
  • @Victor Polevoy You may use qualified names with unscoped enumerators. – Vlad from Moscow May 30 '15 at 10:12
  • Thank you very much. I was using code::blocks and the support for c++11 wasnt enabled. Now it works! – pdf May 30 '15 at 11:00