简体   繁体   中英

Accessing enum values from other class

In my project, I have an enum defined in a class, that is used throughout that class. During refactoring, that enum was moved to another class. So I simply typedef ed it in my original class, like this:

class A {
public:
  enum E {e1, e2};
};
class B {
public:
  typedef A::E E;
};

Now variable definitions, return values, function params, etc. work perfectly. Only when I want to access the values of the enum inside my second class, I still have to qualify them with the surroundig class's name,
eg E e = A::e1;

Is there a way to avoid this, or do I have to copy that into every occurance of the enum values?

You put each enumeration into a nested class that you can typedef within your own class:

class A {
public:
  struct E { enum EnumType { e1, e2 } };
};
class B {
public:
  typedef A::E E;
};

Then it's just E::EnumType instead of E but you get full auto-importation.

如果您没有使用c ++ 11,那么您可以查看枚举类。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM