-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomposite.h
More file actions
107 lines (87 loc) · 2.19 KB
/
composite.h
File metadata and controls
107 lines (87 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
//
// composite.h
// commandLab
//
// Created by shen on 16/11/7.
// Copyright © 2016年 shen. All rights reserved.
//
#ifndef composite_h
#define composite_h
#include <iostream>
#include <sstream>
#include <math.h>
#include <string>
using namespace std;
// forward declare to avoid circular dependencies
class Iterator;
//Abstract Base Class
class Base {
public:
Base(){};
//virtual
virtual double evaluate() = 0;
};
//Leaf Class
class Op: public Base {
private:
double value;
public:
Op() : Base(), value(0){};
Op(double val) : Base(), value(val){};
double evaluate() {
return this->value;
};
};
//Composite Base Classes
class Operator: public Base {
protected:
Base* left, *right;
public:
Operator() : Base(){ };
Operator(Base* l, Base* r) : left(l), right(r){ };
Base* get_left() { return left; };
Base* get_right() { return right; };
virtual double evaluate() = 0; //Note: this is implicit in the inheritance, but can also be made explicit
};
class UnaryOperator: public Base {
protected:
Base* child;
public:
UnaryOperator() : Base(){};
UnaryOperator(Base* c) : child(c) { };
virtual double evaluate() = 0; //Note: this is implicit in the inheritance, but can also be made explicit
};
//Composite Classes
class Add: public Operator {
public:
Add() : Operator() { };
Add(Base* left, Base* right) : Operator(left,right) { };
double evaluate() {
return this->left->evaluate() + this->right->evaluate();
};
};
class Sub: public Operator {
public:
Sub() : Operator() { };
Sub(Base* left, Base* right) : Operator(left,right) { };
double evaluate() {
return this->left->evaluate() - this->right->evaluate();
};
};
class Mult: public Operator {
public:
Mult() : Operator() { };
Mult(Base* left, Base* right) : Operator(left,right) { };
double evaluate() {
return this->left->evaluate() * this->right->evaluate();
};
};
class Sqr: public UnaryOperator {
public:
Sqr() : UnaryOperator() { };
Sqr(Base* child) : UnaryOperator(child) { };
double evaluate() {
return pow(this->child->evaluate(),2);
};
};
#endif /* composite_h */