如该问题的标题中所述,是否有语法可以做到这一点?
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
是可能的,所以我希望也可以对子类中的枚举执行此操作。
答案 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
的实例,这样可以访问Fruit
内Food
的成员。像这样:
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;
}