【发布时间】:2019-12-27 05:38:21
【问题描述】:
我正在尝试编写一个数学集合类。我的想法是创建一个名为 Set 的基类。然后我写了 Set 类的两个子类。即FiniteSet 类和CountableSet 类(可以处理无限集)。我现在的问题是这些子类相互依赖,我无法解决这个问题。我也会欣赏这个问题的完全不同的解决方案。
//--------------------------------------------------------
//Set class
//--------------------------------------------------------
class Set
{
public:
//some virtual functions
protected:
//some attributes
};
//--------------------------------------------------------
//FiniteSet class
//--------------------------------------------------------
class FiniteSet : public Set
{
public:
//implements all virtual functions
//function which needs to know CountableSet:
Set unionWith(Set* otherSet)
{
if(typeid(CountableSet) != typeid(*otherSet))
{
//the other set is finite. We can simply add all
//elements from otherSet to this set.
}
else
{
//create a CountableSet and return it
}
}
private:
//some attributes
}
//--------------------------------------------------------
//CountableSet class
//--------------------------------------------------------
class CountableSet : public Set
{
public:
//implements all virtual functions
//function which needs to know FiniteSets
Set intersectWith(Set* otherSet)
{
if(typeid(FiniteSet) == typeid(*otherSet))
{
//do something and return FiniteSet
}
else
{
//do something and return occasionally CountableSet
}
}
private:
//some attributes
}
【问题讨论】:
-
顺便说一句,您可以使用double dispatch 来避免
typeid。 -
这个问题/答案提高了头文件的重要性;)。
标签: c++ inheritance design-patterns dependencies multiple-inheritance