SHARE
TWEET

Untitled

a guest Mar 23rd, 2019 62 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <memory>
  3. #include <string>
  4.  
  5. class Expression {
  6. public:
  7.     virtual int Evaluate() const = 0;
  8.     virtual std::string ToString() const = 0;
  9.     virtual ~Expression() {}
  10. };
  11.  
  12. using ExpressionPtr = std::shared_ptr<Expression>;
  13.  
  14. class Const: public Expression {
  15. private:
  16.     ExpressionPtr left = nullptr;
  17.     ExpressionPtr right = nullptr;
  18.     int value = 0;
  19.  
  20. public:
  21.     Const(const int& _val) : value(_val) {}
  22.  
  23.     int Evaluate() const override {
  24.         return value;
  25.     }
  26.  
  27.     std::string ToString() const override {
  28.         return std::to_string(value);
  29.     }
  30. };
  31.  
  32. class Sum : public Expression {
  33. private:
  34.     ExpressionPtr left = nullptr;
  35.     ExpressionPtr right = nullptr;
  36.  
  37. public:
  38.     Sum(const ExpressionPtr& _left, const ExpressionPtr& _right)
  39.     : left(_left), right(_right) {
  40.     }
  41.  
  42.     int Evaluate() const override {
  43.         return (left->Evaluate() + right->Evaluate());
  44.     }
  45.  
  46.     std::string ToString() const override {
  47.         std::string temp;
  48.         temp += left->ToString();
  49.         temp += " + ";
  50.         temp += right->ToString();
  51.         return temp;
  52.     }
  53. };
  54.  
  55. ExpressionPtr Const(const int& val) {
  56.     std::shared_ptr<Expression> sh(new class Const(val));
  57.     return sh;
  58. }
  59.  
  60. ExpressionPtr Sum(const ExpressionPtr& ex1, const ExpressionPtr& ex2) {
  61.     std::shared_ptr<Expression> sh(new class Sum(ex1, ex2));
  62.     return sh;
  63. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top