-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path18.cpp
80 lines (71 loc) · 1.67 KB
/
18.cpp
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
#include <iostream>
#include <map>
using namespace std;
// issue : virtual function initialization
// issue : public inheritance
// issue : libirary hashtble
class Expression{
public:
virtual double Evaluate (map<string,double> *vars) = 0;
};
class Constant : public Expression{
double value;
public:
Constant(double value){
this->value = value;
}
double Evaluate(map<string,double> *vars){
return value;
}
};
class VariableReference: public Expression{
string name;
public :
VariableReference(string name){
this->name = name;
}
double Evaluate(map<string,double> *vars){
double value = (*vars)[name];
return value;
}
};
class Operation: public Expression {
Expression* left;
char op;
Expression* right;
public:
Operation(Expression* left, char op, Expression* right) {
this->left = left;
this->op = op;
this->right = right;
}
double Evaluate(map<string,double> *vars) {
double x = left->Evaluate(vars);
double y = right->Evaluate(vars);
switch (op) {
case '+': return x + y;
case '-': return x - y;
case '*': return x * y;
case '/': return x / y;
}
throw "Unknown operator";
}
};
int main(){
Expression *e = new Operation(
new VariableReference("x"),
'*',
new Operation(
new VariableReference("y"),
'+',
new Constant(2)
)
);
map<string,double> *vars = new map<string,double>();
(*vars)["x"] = 3;
(*vars)["y"] = 5;
cout << e->Evaluate(vars) << endl;
(*vars)["x"] = 1.5;
(*vars)["y"] = 9;
cout << e->Evaluate(vars) << endl;
}