3

I wrote the following little script:

#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
    enum class Day {sunday, monday, thuesday, wednesday, thursday, friday, saturday};
    Day unusedDay, today = sunday;
}

But i have a problem. When I debug the programm, the compiler says:

error: 'sunday' was not declared in this scope

but there is my enum class. Why sunday isn't declared? How can I change that?

Thanks for answears:)

mep
  • 341
  • 2
  • 11
  • 4
    `sunday` not being accessible like that is half of the point of using `enum class` in the first place. – chris Sep 04 '16 at 14:07
  • 1
    See [scoped enumeration](http://en.cppreference.com/w/cpp/language/enum). – juanchopanza Sep 04 '16 at 14:08
  • 1
    @mep, if you found any of the answers correct, please mark them so by clicking the grey checkmark icon next to the answer, under the downvote arrow, and it should turn green for an answer to be correct – Arnav Borborah Sep 04 '16 at 14:21

2 Answers2

7

Write

Day unusedDay, today = Day::sunday;

The enumerators are in the scope of the enumeration.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
3

You are confusing an enum with an enum class. Suppose your code was this:

enum Day {sunday, monday, thuesday, wednesday, thursday, friday, saturday};
Day unusedDay, today = sunday;

Then the above code would compile, since normal enum's have values that are visible globally, so you can access them like Day unusedDay, today = sunday;. As for enum classes, the rules differ a little. For your example to work, you would to write the code like this:

enum Day {sunday, monday, thuesday, wednesday, thursday, friday, saturday};
Day unusedDay, today = Day::sunday;

If you look at the documentation for enum's vs enum classes, you see this:

Enum

Declares an unscoped enumeration type whose underlying type is not fixed -

Note the use of the word unscoped here meaning the variable is available just with it's name.

Enum Class

declares a scoped enumeration type whose underlying type is int (the keywords class and struct are exactly equivalent)

As seen here, an enum class is scoped, and accessibly only as enumname::value;

(Source)

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88