从其他类访问枚举值 [英] Accessing enum values from other class
问题描述
在我的项目中,我在一个类中定义了一个枚举,该枚举在整个该类中使用。在重构期间,该枚举被移至另一个类。因此,我在原班上简单地 typedef
编辑了它,就像这样:
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;
};
现在变量定义,返回值,函数参数等都可以正常工作。仅当我想访问第二个类中的枚举值时,我仍然必须使用周围环境类的名称来限定它们,例如
E e = A :: e1;
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,
e.g. 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?
推荐答案
您将每个枚举放入嵌套的类中,您可以在自己的类中键入def :
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;
};
然后只是 E :: EnumType
的 E
,但您会获得完全的自动导入。
Then it's just E::EnumType
instead of E
but you get full auto-importation.
这篇关于从其他类访问枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!