Why do people use enums in C++ as constants when they can use const
?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
It's partly because older compilers did not support the declaration of a true class constant
so had to do this
For this reason, many portable libraries continue to use this form.
The other reason is that enums can be used as a convenient syntactic device to organise class constants into those that are related, and those that are not
vs
Enums are distinct types, so you can do type-oriented things like overloading with them:
Some debuggers will show the enumeration name instead of its value when debugging. This can be very helpful. I know that I would rather see
day_of_week = MONDAY
thanday_of_week = 1
.An enumeration implies a set of related constants, so the added information about the relationship must be useful in their model of the problem at hand.
I like the automatic behavior that can be used with enums, for example:
Then it is easy to loop until LAST, and when a new state (or whatever is represented) is added, the logic adapts.
Add something...
The loop adapts...
Bruce Eckel gives a reason in Thinking in C++:
[Edit]
I think it would be more fair to link Bruce Eckel's site: http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html.