如何通过主类类型的对象访问子类内部的枚举?

时间:2018-07-09 01:49:24

标签: c++ enums

如该问题的标题中所述,是否有语法可以做到这一点?

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是可能的,所以我希望也可以对子类中的枚举执行此操作。

2 个答案:

答案 0 :(得分:1)

类似这样的东西:

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

答案 1 :(得分:1)

更新

您可以在Fruit内创建Food的实例,这样可以访问FruitFood的成员。像这样:

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的子类,因此多重继承是另一个问题,也许this可以帮助您

OLD

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

#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的类别设为Fruit 像这样:

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