Advertisement
Dzham

Untitled

Feb 6th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. class con: public Expression {
  2. private:
  3. int x;
  4.  
  5. public:
  6. con(int a) {
  7. x = a;
  8. }
  9. int Evaluate() const {
  10. return x;
  11. }
  12. std::string ToString() const {
  13. return std::to_string(x);
  14. }
  15. };
  16.  
  17. class sum : public Expression {
  18. private:
  19. ExpressionPtr x;
  20. ExpressionPtr y;
  21.  
  22. public:
  23. sum(ExpressionPtr a, ExpressionPtr b) : x(a), y(b) {}
  24.  
  25. int Evaluate() const {
  26. return x->Evaluate() + y->Evaluate();
  27. }
  28. std::string ToString() const {
  29. return (x->ToString() + " + " + y->ToString());
  30. }
  31. };
  32.  
  33. class product : public Expression {
  34. private:
  35. ExpressionPtr x;
  36. ExpressionPtr y;
  37.  
  38. public:
  39. product(ExpressionPtr a, ExpressionPtr b) : x(a), y(b) {}
  40.  
  41. int Evaluate() const {
  42. return x->Evaluate() * y->Evaluate();
  43. }
  44. std::string ToString() const {
  45. std::string e1 = x->ToString();
  46. std::string e2 = y->ToString();
  47. size_t summ = e1.find('+');
  48. size_t left = e1.find('(');
  49. if (summ != -1) {
  50. if (left == -1 || (left != -1 && (summ < left || e1.rfind('+') > e1.rfind(')')))) {
  51. e1 = "(" + e1 + ")";
  52. }
  53. }
  54. summ = e2.find('+');
  55. left = e2.find('(');
  56. if (summ != -1) {
  57. if (left == -1 || (left != -1 && (summ < left || e2.rfind('+') > e2.rfind(')')))) {
  58. e2 = "(" + e2 + ")";
  59. }
  60. }
  61. return e1 + " * " + e2;
  62. }
  63. };
  64.  
  65. ExpressionPtr Const(int a) {
  66. return ExpressionPtr(new con(a));
  67. }
  68.  
  69. ExpressionPtr Sum(const ExpressionPtr& a, const ExpressionPtr& b) {
  70. return ExpressionPtr(new sum(a, b));
  71. }
  72.  
  73. ExpressionPtr Product(const ExpressionPtr& a, const ExpressionPtr& b) {
  74. return ExpressionPtr(new product(a, b));
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement