mercredi 21 août 2019

How to write a base class whose child classes depend on each other?

I'm trying to write a mathematical set class. My idea was to make an base class which is called Set. Then i wrote two child classes of the Set class. Namely the FiniteSet class and the CountableSet class (which can deal with infinite Sets). My problem is now that those child classes depend on each other and I cannot solve this. I will also appreciate completely different solutions to this problem.

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

Aucun commentaire:

Enregistrer un commentaire