How to access an enum inside sub-class via object of main-class type?
正如这个问题的标题中所提到的,是否有语法可以做到这一点?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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. //... } |
我更喜欢
更新
您可以在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Food : public Edible { public: class Fruit : public FruitBase { public: enum Type{ APPLE, GRAPES, ORANGE }; }; static Fruit fruit; // -> this is what I was talking about enum { CAKE, CHOCOLATE }; }; int main() { Food food; auto apple = food.fruit.APPLE; // this is not so different of your 'typeG' } |
现在关于
旧的
为什么不使用这样的继承:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <iostream> class Fruit { public: enum Type { APPLE, GRAPES, ORANGE }; }; class Food : public Fruit { public: enum Foods { CAKE, CHOCOLATE }; }; int main() { Food food; auto apple = food.Type::APPLE; } |
如果你真的像你说的那样喜欢
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <iostream> class Fruit { public: enum { APPLE, GRAPES, ORANGE }; }; class Food : public Fruit { public: enum Foods { CAKE, CHOCOLATE }; }; int main() { Food food; auto apple = food.APPLE; } |
像这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Food { public: class Fruit { public: enum Type { APPLE, GRAPES, ORANGE, }; Type type; }; Fruit fruit; enum class Foodies{ CAKE, CHOCOLATE }; Foodies foodies; }; void func() { typedef Food::Fruit::Type FruitType; Food snack; auto typeA = snack.fruit.type = FruitType::APPLE; } |