Do enum values ​​know as global variables?

I have two enumerations, and if in one enumeration there is one value with the same name as the value in another enumeration:

enum A {joe, bob, doc};
enum B {sunday, monday, doc};

The compiler (Visual Studio) complains about overriding doc, which means that it treats it as a global variable. This is true? This is not the behavior that I expect, and it forces me to manage the names of all the enumeration elements in my project.

Any ideas will help.

+5
source share
6 answers

Enumerators in C ++ 03 have the same scope as enums.

enum     xxx    {    yyy,       zzz       };
          ^           ^          ^ 
    enumeration    enumerator enumerator

It is sometimes convenient, sometimes it is not.

++ 0x enum class es, # enums. ( ), yyy zzz ​​ , xxx

+5

namespace A
{
    enum A {joe, bob, doc};
}
namespace B
{
    enum B {sunday, monday, doc};
}

" , ",

A::doc;
B::doc;

, , enum , , .

, enum , :

struct A
{
    enum Enum {joe, bob, doc};
};
struct B
{
    enum Enum {sunday, monday, doc};
};

, ,

A::doc;
B::doc;

  • ,

  • ,

  • typedef.

, , ,

  • , , . A::Enum.

, & hellip;

hth.,

+9

. .

, , enum. .

, , .;)

, , . :

enum InstrumentType { itStock, itEquityOption, itFutureOption };

.

+7
source

If you want them to be global, fix the problem and avoid polluting the namespace by throwing it enumin the namespace:

namespace A
{
    enum A {joe, bob, doc};
}
namespace B
{
    enum B {sunday, monday, doc};
}

A::doc;
B::doc;
+4
source

Enumeration values ​​exist in any area in which it is declared enum.

The following actions, for example:

enum A {joe, bob, doc};
namespace C { enum B {sunday, monday, doc}; }

or

class A_class { enum A {joe, bob, doc}; };
class B_class { enum B {sunday, monday, doc}; };
+2
source

The enumeration values ​​have the scope of the enumeration itself, that is, the scope of the declaration. For instance:

enum A {value = 30};

int main()
{
   enum B {value = 32};
   int x = value;
}

x will be 32.

+1
source

All Articles