0

I am confused with a project that I study for a course. I have to build a tree-expression, I know how the algorithm works, but I have difficulties with setting up the nodes.

The instructor gave us this class: Expression Node Where it has 2 other subclasses: Constant Node and Operator Node?

and in the "Expression Tree class": Where am I building the tree-expression? I have a Stack with this type : Expression Node

my question is: after I assign an operator or an constant, how can I push it to the Stack, since the types are different.

i am working with C++ thank you.

Přemysl Šťastný
  • 1,676
  • 2
  • 18
  • 39
Makaveli
  • 309
  • 1
  • 3
  • 9

2 Answers2

1

Apply polymorphism: Push pointers ( or references ) to your nodes. Since your stack contains elements of type "ExpressionNode", it can accept all types that derive from it ( Constant and Operator).

Clusty
  • 117
  • 7
0

If you have access to boost, boost::variant is what you are looking for. See this, it is OO version of union.

header file

#include <boost/variant.hpp>

stack<boost::variant<int,char>> s;
s.push('+');
s.push(1);