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

前端 未结 12 1456
梦毁少年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:03

    It's partly because older compilers did not support the declaration of a true class constant

    class C
    {
      const int ARealConstant = 10;
    };
    

    so had to do this

    class C
    {
      enum { ARealConstant = 10 };
    };
    

    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

    class DirectorySearcher
    {
      enum options
      {
        showFiles = 0x01,
        showDirectories = 0x02,
        showLinks = 0x04,
      };
    };
    

    vs

    class Integer
    {
       enum { treatAsNumeric = true };
       enum { treatAsIntegral = true };
       enum { treatAsString = false };
    };
    

提交回复
热议问题