Subject: code for posting -start point for hw6 // Expression parsing by Ira Pohl // Extend this example as indicated in HW6 #include //Abstract Base Class + Reference Collected Type class Token { //allowed are integers and binary operators protected: friend class Expr; friend ostream& operator<<(ostream&, const Expr&); Token(){ use = 1; } virtual void print(ostream&) = 0; virtual ~Token() {} //note virtual destructor virtual int eval() = 0; private: int use; //reference count }; class Expr { public: friend class Token; friend ostream& operator<<(ostream&, const Expr&); Expr(int); //constant Expr(char*, Expr, Expr); //binary operator Expr(const Expr& t) { p = t.p; ++p -> use;} ~Expr() {if (--p ->use == 0) delete p; } void operator=(const Expr& t); int eval() {return p->eval();} private: Token* p; //polymorphic hierarchy }; void Expr:: operator=(const Expr& t) { ++t.p -> use; if ( --p -> use == 0) delete p; p = t.p; } ostream& operator<<(ostream& o, const Expr& t) { t.p -> print(o); return (o); } class IntToken: public Token { public: friend class Expr; int eval(){ return n;} private: int n; void print(ostream& o) { o << n ;} IntToken(int k): n (k) {} }; class BinaryToken: public Token { public: friend class Expr; int eval(); private: char* op; Expr left; Expr right; BinaryToken(char* a, Expr b, Expr c): op(a), left(b), right(c){} void print (ostream& o) {o << "(" << left << op << right << ")";} }; int BinaryToken::eval() { switch (op[0]){ case '-': return (left.eval() - right.eval()); case '+': return (left.eval() + right.eval()); case '*': return (left.eval() * right.eval()); default: cerr << "no operand\n" << endl; return 0; } } Expr::Expr(int n) { p = new IntToken(n); } Expr::Expr(char* op, Expr left, Expr right) { p = new BinaryToken(op, left, right); } int main() { Expr t1 = Expr("*", Expr("-", 5, 8), Expr("+", 6, 4)); Expr t2 = Expr("+", Expr("-", 4, 1), Expr("+", t1, 2)); cout << "t1 = " << t1 << " ; t2 = " << t2 << endl; cout << "t1:" << t1.eval() << " t2:" << t2.eval() << endl; }