开发者

Scope of enumerators

开发者 https://www.devze.com 2023-03-31 11:13 出处:网络
In the following, I don\'t know if i\'m confusing enums in C# with C++ but I thought you could only access enumerators in enum using Forms::shape which actually gives an error.

In the following, I don't know if i'm confusing enums in C# with C++ but I thought you could only access enumerators 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 to be accessed outside of enum without a scope operator and how can i prevent this behavior?


Well, because enums do not form a declarative scope. It is just the way it is in C++. You want to envelope these enum constants in a dedicated scope, make one yourself: use a wrapper class or namespace.

The upcoming C++ standard will introduce new kind of enum that does produce its own scope.


In your example, the enum isn't declared inside a class so it has no particular scope. You could define a struct - a struct is a class where all members are public in C++ - that contains your enum, and use the name of that class to provide the scope.

You could also create a namespace and place your enum inside it as well. But that might be overkill.


I'd suggest that the underlying reason derives from C compatibility.


C++11 introduces scoped enumerations, which keep the namespace clean and also prevent unintentional combinations with int types. Scoped enums are declared with the keyword sequence enum class.

By using scoped enumerations, your 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

精彩评论

暂无评论...
验证码 换一张
取 消