Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an "enum is not a class or namespace" error - C++ [duplicate]

Tags:

c++

enums

I declared an enum (called Direction) in a header file:

enum Direction {LEFT, RIGHT};

Then, i have a constructor that takes a Direction value and set it for another Direction variable (stringDirection).

bool InformationWidget::move(Direction direction){
    stringDirection=direction;

return true;
}

And finally, i have an if statement that checks the value of it:

if (stringDirection == Direction::RIGHT)

This is where i'm getting the error, at that if statement.. any ideas? I tried looking around at previous threads but didn't find anything useful.

Thanks!

EDIT:

Here are my files:

Widget.h

enum class Direction {LEFT, RIGHT};

class Widget {
public:
     virtual bool...
     ...
};

information.h

class InformationWidget: public Widget {
public:
    ...
    Direction stringDirection;
    ...
};

information.cpp

void InformationWidget::show(){

...

if (stringDirection == LEFT) {
... }
}
like image 570
Gambit2007 Avatar asked Oct 28 '15 23:10

Gambit2007


People also ask

Can enum have duplicate values in C?

CA1069: Enums should not have duplicate values (code analysis) - .

Can enum have duplicate values?

1. Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

How do you declare an enum?

An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.

Can we add constants to enum without breaking existing code?

4) Adding new constants on Enum in Java is easy and you can add new constants without breaking the existing code.


1 Answers

Declare your enum as enum class or enum struct if you want a scoped enum, i.e. to require the enumerators to be prefixed Direction:::

enum class Direction {LEFT, RIGHT};

Otherwise if you want an old C-style enum then you need to omit the namespace qualifier Direction:: that the error message is complaining about:

if (stringDirection == RIGHT)

Notice that in the latter case the enumerator identifiers will be placed in the global namespace, which might cause them to clash with other identifiers.

like image 88
emlai Avatar answered Sep 28 '22 17:09

emlai