Enumerator Volume

In the following, I don't know if I am confusing enums in C # with C ++, but I thought you could only use enums in enum using Forms::shape , which actually gives an error.

 int main() { enum Forms {shape, sphere, cylinder, polygon}; Forms form1 = Forms::shape; // error Forms form2 = shape; // ok } 

Why is shape allowed access outside of enum without a scope operator and how can I prevent this behavior?

+6
source share
4 answers

Well, because transfers do not form a declarative area. This is the same as in C ++. You want to go around these enumeration constants in the selected area, do one yourself: use a wrapper class or namespace.

The upcoming C ++ standard will introduce a new kind of enumeration that creates its own scope.

+5
source

In your example, an enumeration is not declared inside the class, so it does not have a specific scope. You can define struct - struct - this is a class in which all members are publicly available in C ++ - that contains your enumeration, and use the name of this class to provide the scope.

You can also create a namespace and put your enum in it. But this may be redundant.

+1
source

I would suggest that the main reason stems from C compatibility.

0
source

C ++ 11 introduces copied enumerations that keep the namespace clean and also prevent unintended combinations with int types. Zero enumerations are declared using the enum class keyword sequence.

Using the highlighted enumerations, the above example then turns into this:

 int main() { enum class Forms {shape, sphere, cylinder, polygon}; // mind the "class" here Forms form1 = Forms::shape; // ok Forms form2 = shape; // error } 
0
source

Source: https://habr.com/ru/post/896176/


All Articles