Advertisement
RobertDeMilo

YB5.9 Задача разбора арифметического выражения Описание решения

Apr 14th, 2024
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <memory>
  4.  
  5. using namespace std;
  6.  
  7. class Node
  8. {
  9. public:
  10.     virtual int Evaluate()
  11.     {
  12.         return 0;
  13.     }
  14.  
  15. };
  16.  
  17. class Digit: public Node
  18. {
  19. public:
  20.     Digit(int d):d_(d){}
  21.  
  22.     int Evaluate() override
  23.     {
  24.         return d_;
  25.     }
  26.  
  27. private:
  28.     const int d_;
  29. };
  30.  
  31. class Variable: public Node
  32. {
  33. public:
  34.     Variable(const int&x):x_(x){}
  35.  
  36.     int Evaluate() override
  37.     {
  38.         return x_;
  39.     }
  40.  
  41. private:
  42.     const int &x_; // сохраняем ссылку на некторую внешнюю переменную
  43. };
  44.  
  45. class Operation: public Node
  46. {
  47. public:
  48.     //Operation(Node&, Node&)
  49.     Operation(char op,shared_ptr<Node> left, shared_ptr<Node> right):
  50.         op_(op), left_(left), right_(right)
  51.     {
  52.  
  53.     }
  54.     int Evaluate() override
  55.     {
  56.         if(op=='*')
  57.         {
  58.             return left_->Evaluate() * right_->Evaluate();
  59.         }
  60.         else if(op=='+')
  61.         {
  62.             return left_->Evaluate() + right_->Evaluate();
  63.         }
  64.         else if(op=='-')
  65.         {
  66.             return left_->Evaluate() - right_->Evaluate();
  67.         }
  68.         return 0;
  69.     }
  70.  
  71. private:
  72.     const char op_;
  73.     shared_ptr<Node> left_, right_;
  74. };
  75.  
  76. Node Parse(const string&  tokens, int& x)
  77. {
  78.  
  79. }
  80.  
  81. int main()
  82. {
  83.     string tokens = "5+7-x*x+x";
  84.     //cout<<"Enter experssion: ";
  85.     //cin>>tokens;
  86.     //int x;
  87.     //auto expr = Parse(tokens, x);
  88.  
  89.     cout<<"Enter x: ";
  90.     while (cin>>x)
  91.     {
  92.         cout<<expr->Evaluate()<<endl;
  93.     }
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement