Suppose we have an enum
like the following:
enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};
I want to crea
While C++ (excluding C++11) has enums, the values in them are "leaked" into the global namespace.
If you don't want to have them leaked (and don't NEED to use the enum type), consider the following:
class EnumName {
public:
static int EnumVal1;
(more definitions)
};
EnumName::EnumVal1 = {value};
if ([your value] == EnumName::EnumVal1) ...
This will be sufficient to declare your enum variable and compare it:
enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};
Days day = Saturday;
if (day == Saturday) {
std::cout << "Ok its Saturday";
}
Enums in C++ are like integers masked by the names you give them, when you declare your enum-values (this is not a definition only a hint how it works).
But there are two errors in your code:
enum
all lower caseDays.
before Saturday.if (day == YourClass::Saturday){}
This code is wrong:
enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};
Days day = Days.Saturday;
if (day == Days.Saturday)
Because Days
is not a scope, nor object. It is a type. And Types themselves don't have members. What you wrote is the equivalent to std::string.clear
. std::string
is a type, so you can't use .
on it. You use .
on an instance of a class.
Unfortunately, enums are magical and so the analogy stops there. Because with a class, you can do std::string::clear
to get a pointer to the member function, but in C++03, Days::Sunday
is invalid. (Which is sad). This is because C++ is (somewhat) backwards compatable with C, and C had no namespaces, so enumerations had to be in the global namespace. So the syntax is simply:
enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};
Days day = Saturday;
if (day == Saturday)
Fortunately, Mike Seymour observes that this has been addressed in C++11. Change enum
to enum class
and it gets its own scope; so Days::Sunday
is not only valid, but is the only way to access Sunday
. Happy days!
First of all, make 'E' in enum, 'e' as a lower case.
Second, drop type name 'Days' in 'Days.Saturday'.
Third ...buy yourself a good C++ book.
You are looking for strongly typed enumerations, a feature available in the C++11 standard. It turns enumerations into classes with scope values.
Using your own code example, it is:
enum class Days {Saturday, Sunday, Tuesday,Wednesday, Thursday, Friday};
Days day = Days::Saturday;
if (day == Days::Saturday) {
cout << " Today is Saturday !" << endl;
}
//int day2 = Days::Sunday; // Error! invalid
Using ::
as accessors to enumerations will fail if targeting a C++ standard prior C++11. But some old compilers doesn't supported it, as well some IDEs just override this option, and set a old C++ std.
If you are using GCC, enable C+11 with -std=c++11 or -std=gnu11 .
Be happy!