关于C++:如何通过主类类型的对象访问子类中的枚举?

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.

    //...


}

我更喜欢typeG的语法。我的第二个选择是typeA。我目前正在代码中使用typeO,但我需要从对象snack而不是类Food访问这些枚举常量。由于typeC是可能的,我希望还有一种方法可以在子类中的枚举上实现这一点。


更新

您可以在Food中创建Fruit的实例,这样您就可以访问FoodFruit的成员。这样地:

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'
}

现在关于Fruit需要是Food的子类,但是Fruit已经是FruitBase的子类,所以多重继承是另一个问题,也许这对你有帮助。

旧的

为什么不使用这样的继承:

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;
}

如果你真的像你说的那样喜欢typeG,你可以使enum Type的范围成为类水果。这样地:

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;
}