【发布时间】:2018-05-13 14:50:55
【问题描述】:
给定一个类,该类具有一些定义类类型的枚举,如下例所示:
class Fruit {
public:
enum class FruitType {
AppleType = 0,
OrangeType = 1,
BananaType = 2,
};
Fruit(FruitType type) : type_(type) {}
FruitType fruit_type() const { return type_; }
private:
FruitType type_;
};
以及从它派生的共享相同枚举的类:
class DriedFruit : public Fruit {
public:
// Some Dried specific methods.
};
是否可以通过每个特定的枚举值为 Fruit 和 DryFruit 定义不同的类型:
class Apple // Fruit with FruitType = AppleType
class Orange // Fruit with FruitType = OrangeType
class Banana // Fruit with FruitType = BananaType
class DriedApple // DriedFruit with FruitType = AppleType
class DriedOrange // DriedFruit with FruitType = OrangeType
class DriedBanana // DriedFruit with FruitType = BananaType
所以 Apple、Orange 和 Banana 3 个类是不同的类型,DriedApple、DriedOrange、DriedBanana 3 个类是不同的类型。
我的问题有点类似于How to define different types for the same class in C++,只是我想将有关类类型的信息显式存储为类中的枚举成员变量,并为所有不同类型提供一个公共基类。
最有效的方法是什么?
编辑: 主要用例如下 - 在我的应用程序中,有某些方法只期望 Apple 作为输入,或者只期望 Orange 作为输入,还有许多方法不关心它是哪种水果。
将 Fruit 传递给只期望 Apple 的方法感觉不安全/晦涩难懂,同时有许多方法不关心它是哪种类型,因此拥有 3 个不同的类型也不是一个好的选择。
主要工作流程如下: 从一些输入参数构建一个水果,然后 传递它并将其作为水果处理,然后在某个时候 如果是 Apple,则将 Fruit 转换为具体的 Apple 类型,并进一步处理它,从那时起将其类型限制为 Apple。
【问题讨论】:
-
你链接的问题的答案不是回答这个问题吗?
-
使
type_受保护并让每个派生类在构造函数中适当设置它有什么问题吗?? -
这看起来有点 XY 问题。为什么您真的需要为
Fruit的特定实例提供不同类型?在公共类中实现的专用接口?后者闻起来是设计缺陷。 -
@user0042 - 很可能是 XY 问题 - 我已经扩展了我的问题以提示用例
-
@Ilya Kobelevskiy 我认为您需要扩展此位
then at some point if it is an Apple, further process it, restricting it type to an Apple from that point onwards.您希望它在代码中看起来如何?因为我认为这可能是你的“X”,而这个枚举是你的“Y”。
标签: c++ c++11 inheritance types