I have a set of enum values defined in the "Foo" class (below).
namespace Fii
{
class Foo
{
struct Bar
{
enum Baz
{
BAZ1,
BAZ2,
BAZ3
};
};
};
};
I am using a struct to reduce the scope of Baz enum values as well as show there are a group of related values.
My objective is to assign a value from an enum type to a variable. Using the class definition above, one can do this:
Fii::Foo::Bar::Baz myValue = Fii::Foo::Bar::BAZ1 (Works in both C++98 and C++11)
However, I feel that:
To improve readiness, I I re-factored the code to:
namespace Fii
{
class Foo
{
enum Baz
{
BAZ1,
BAZ2,
BAZ3
};
};
};
Using this new class definition, one can do this:
Fii::Foo::Baz myValue = Fii::Foo::Baz::BAZ1 (Works in C++11 only)
Fii::Foo::Baz myValue = Fii::Foo::BAZ1 (Should work on C++98 and C++11 - not tested)
Q1) Why is Fii::Foo::Bar::Baz myValue = Fii::Foo::Baz::BAZ1 only working on C++11 ?
Q2) In C++98, is there a way to write Fii::Foo::Baz myValue = Fii::Foo::Baz::BAZ1 ? You are allowed to make any changes you like in the class definition.
Environment: - Clang compiler with C++11 support - Xcode 4 - Mac OS OS 10.8
Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
Yes, but unlike an enum, you have to specify a type for the values. You also have to make sure the index won't be higher than the number of cells.
You can't do it, since the language does not allow you. And for a good logical reason: subclassing an enum would only make sense if you could remove some enum values from the subclass, not add new ones. Otherwise you would break the Liskov Substitution Principle.
C++11 adds class enums. It also adds a new way of accessing old-style enum values, which is what you are seeing here.
enum Foo { FOO1, FOO2, FOO3 }; // old-style enum
Foo f1 = Foo::FOO1; // OK in C++11, error in C++98.
Foo f2 = FOO1; // OK in C++98 and C++11 (for backward compatibility)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With