Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <memory>
- #include <string>
- class Expression {
- public:
- virtual int Evaluate() const = 0;
- virtual std::string ToString() const = 0;
- virtual ~Expression() {}
- };
- using ExpressionPtr = std::shared_ptr<Expression>;
- class Const: public Expression {
- private:
- ExpressionPtr left = nullptr;
- ExpressionPtr right = nullptr;
- int value = 0;
- public:
- Const(const int& _val) : value(_val) {}
- int Evaluate() const override {
- return value;
- }
- std::string ToString() const override {
- return std::to_string(value);
- }
- };
- class Sum : public Expression {
- private:
- ExpressionPtr left = nullptr;
- ExpressionPtr right = nullptr;
- public:
- Sum(const ExpressionPtr& _left, const ExpressionPtr& _right)
- : left(_left), right(_right) {
- }
- int Evaluate() const override {
- return (left->Evaluate() + right->Evaluate());
- }
- std::string ToString() const override {
- std::string temp;
- temp += left->ToString();
- temp += " + ";
- temp += right->ToString();
- return temp;
- }
- };
- ExpressionPtr Const(const int& val) {
- std::shared_ptr<Expression> sh(new class Const(val));
- return sh;
- }
- ExpressionPtr Sum(const ExpressionPtr& ex1, const ExpressionPtr& ex2) {
- std::shared_ptr<Expression> sh(new class Sum(ex1, ex2));
- return sh;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement