Why do people use enums in C++ as constants while

2019-01-16 16:19发布

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

12条回答
神经病院院长
2楼-- · 2019-01-16 16:53

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 };
};
查看更多
Emotional °昔
3楼-- · 2019-01-16 16:58

Enums are distinct types, so you can do type-oriented things like overloading with them:

enum Color { Red,Green,Blue };
enum Size { Big,Little };

void f( Color c ) {
}

void f( Size s ) {
}

int main() {
    f( Red );
    f( Big );
}
查看更多
何必那么认真
4楼-- · 2019-01-16 16:59

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 than day_of_week = 1.

查看更多
冷血范
5楼-- · 2019-01-16 17:00

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.

查看更多
淡お忘
6楼-- · 2019-01-16 17:00

I like the automatic behavior that can be used with enums, for example:

enum {NONE, START, HEY, HO, LAST};

Then it is easy to loop until LAST, and when a new state (or whatever is represented) is added, the logic adapts.

for (int i = NONE; i < LAST; i++)
{
    // Do stuff...
}

Add something...

enum {NONE, START, HEY, WEE, HO, LAST};

The loop adapts...

查看更多
SAY GOODBYE
7楼-- · 2019-01-16 17:06

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 <iostream>
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.

查看更多
登录 后发表回答