Home > Software design >  Is there a way to use type of three classes inside each other?
Is there a way to use type of three classes inside each other?

Time:12-14

When I was trying to write a library for myself that handles the algebraic expressions I encountered a problem. I have three classes: divide, expression, groupexpression. I want to use divide type in expression and group expression. And use expression type in group expression. The problem is I also need to use group expression type in divide class like this:

// * (2x)/(4b)
class Divide{
    //...
    GroupExpression numerator, denumerator;
    //...
}
// * -2Pow(x, 3)
class Expression{
    //...
    Divide pow, multiple;
    //...
}
// * (2x-3ax Pow(x, 5))/(ax-2x)
class GroupExpression : Divide{
    //...
    vector<Expression> group;
    //...
}

But this does not meet with programing rules that we should declare it first to use it. How to sort this to meet the rules?

I've been thinking about the exception but didn't found any answer. Didn't find any solution on internet because I don't know how to search this problem so I appreciate any help.

Is it possible doing this this?

CodePudding user response:

Without knowing a lot more about what you are trying to do, I don't know the right design.

But a typical approach would involve having a BaseExpression class. Then you could have child classes like DivideExpression that have member variables named denominator and numerator which are themselves of class BaseExpression. And those expressions might be concrete instances of another class like ExpressionTerm. But DivideExpression doesn't need to know that detail. All that it needs to know is that they are of type BaseExpression, which was declared first.

And now any methods you want available for all, like printing and evaluation, should be methods on BaseExpression. Going further you can then have a parser to turn a text expression into a parse tree that is then turned into the appropriate Expression objects.

Note that you don't probably don't need a generic GroupExpression because that need is covered by being able to create a recursive tree of specific kinds of expressions. None of which need to know more about their subexpressions other than that they inherit from BaseExpression.

  • Related