Why do people use enums in C++ as constants while they can use const?

前端 未结 12 1448
梦毁少年i
梦毁少年i 2020-12-08 02:28

Why do people use enums in C++ as constants when they can use const?

12条回答
  •  情深已故
    2020-12-08 03:04

    Bruce Eckel gives a reason in Thinking in C++:

    In older versions of C++, static const was not supported inside classes. This meant that const was useless for constant expressions inside classes. However, people still wanted to do this so a typical solution (usually referred to as the “enum hack”) was to use an untagged enum with no instances. An enumeration must have all its values established at compile time, it’s local to the class, and its values are available for constant expressions. Thus, you will commonly see:

    #include 
    using namespace std;
    
    class Bunch {
      enum { size = 1000 };
      int i[size];
    };
    
    int main() {
      cout << "sizeof(Bunch) = " << sizeof(Bunch) 
           << ", sizeof(i[1000]) = " 
           << sizeof(int[1000]) << endl;
    }
    

    [Edit]

    I think it would be more fair to link Bruce Eckel's site: http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html.

提交回复
热议问题