【发布时间】:2018-12-16 15:42:54
【问题描述】:
正如这个问题的标题中提到的,有没有语法可以做到这一点?
class Food : public Edible {
public:
class Fruit : public FruitBase { //note: Fruit must be a class and a subclass of Food.
public:
enum Type { //note: Type must be inside Fruit and must be a plain enum.(not enum class)
APPLE,
GRAPES,
ORANGE,
};
//...
};
enum { CAKE, CHOCOLATE };
//...
};
void func(){
Food snack;
//...
auto typeA = snack.Fruit::APPLE; //<---this is syntax error.
auto typeG = snack.GRAPES; //<---also syntax error.
auto typeO = Food::Fruit::ORANGE; //<---this is OK, but not my target.
auto typeC = snack.CAKE; //<---this is OK.
//...
}
我更喜欢typeG 的语法。我的第二个偏好是typeA。我目前在我的代码中使用typeO,但我需要从对象snack 而不是类Food 访问这些枚举常量。由于typeC 是可能的,我希望还有一种方法可以在子类中的枚举上执行此操作。
【问题讨论】:
-
这样做能解决什么问题?
-
@JamesPoag 感谢您的链接。但是在我提出问题的项目部分,我们决定选择普通枚举。我们对其进行了研究并权衡了优缺点。但是在我们的项目中有一部分我们使用
enum class。建议我们不要只关注互联网上的best practices信息并自行确认,哪个更好用于特定类型的情况/问题。 -
@Nicky,很抱歉没有公开我的代码的更多细节。这是公司项目的一部分。问题是这样的:
Fruit子类名称存在于几个彼此不连接的Food类(具有不同的类名称)上。所以Fruit子类是我们使用的数据结构的约定。Fruit::Type用作在函数中传递的参数。每次我们传递Fruit::Type对象,目前,我们还指定Food,所以它是void testFunc(Food1::Fruit::APPLE)。但是有几个Food*类。这实际上是关于代码的可维护性。 -
我想我现在的问题的答案是
No, there's no syntax support yet。但我想auto typeA = snack.Fruit::APPLE;语法在 c++ 中得到支持很好。