对于以下问题(最重要的是 C++),什么是好的做法?
我想实现两个(以及后来的更多)非常相似但不兼容的类。例如,我将它们命名为 class Apple
和 class Orange
.显然,then 具有共同的属性,例如物种、年龄、位置等等,但是 apple 对象永远不应该分配给 orange 变量。
更重要的是:应该有成员函数接受(或返回)自己的类而不是其他的。例如,Apple 的类:Apple[] getAllFromTheSameTree();
Orange 类将有:Orange[] getAllFromTheSameTree();
还有类似 void addToSameTree(Apple)
的东西等等,记住苹果不能和橙子在同一棵树上。
一个想法是拥有一个抽象根类 ( class Fruit
) 来定义公共(public)属性。但这将允许函数接受 Fruit
类型参数,我想禁止 - 如果可能的话)。
另一个想法是模板:Fruit<Apple>
和 Fruit<Orange>
(Apple 和 Orange 在这里是一些虚拟的空类型)。
最佳答案
One idea is to have an abstract root class (class Fruit) that would define the common properties
是的,这就是我建议您的想法。
But that would allow a function to accept a Fruit type parameter, which I want to prohibit - if possible).
好吧,这不是问题。因为是抽象的,所以不能有 Fruit
类型的对象。
例如具有此签名的函数:
void consume_fruit(Fruit& fruit)
将接受任何种类的水果( Apple
, Orange
)。自 Fruit
是抽象的,它不会接受 Fruit
类型的对象仅仅是因为 Fruit
类型的对象不存在。
集合的相似性,例如std::vector<std::shared_ptr<Fruit>>
将保存从 Fruit
派生的类型的对象( Apple
, Orange
) 但同样不能有 Fruit
类型的对象.
关于c++ - 相似但不兼容的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41521593/