mep
mep

Reputation: 351

error: 'enumElement' was not declared in this scope

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:)

Upvotes: 3

Views: 5248

Answers (2)

Arnav Borborah
Arnav Borborah

Reputation: 11779

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)

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

Write

Day unusedDay, today = Day::sunday;

The enumerators are in the scope of the enumeration.

Upvotes: 7

Related Questions