#include <iostream>
#include <map>
#include <stack>
using namespace std;
class Expression{
public:
virtual int interpret(map<char, int>var) = 0;
virtual ~Expression(){}
};
//变量表达式
class VarExpression : public Expression{
char key;
public:
VarExpression(const char & key){ this->key = key; }
int interpret(map<char, int> var)override{
return var[key];
}
};
//符号表达式
class SymbolExpression : public Expression{
//运算符左右有两个参数
protected:
Expression * left;
Expression * right
;public:
SymbolExpression(Expression * left, Expression * right):left(left), right(right){}
};
//加法运算
class AddExpression : public SymbolExpression{
public:
AddExpression(Expression * left, Expression * right):SymbolExpression(left, right){}
int interpret(map<char, int> var) override
{
return left->interpret(var) + right->interpret(var);
}
};
//减法运算
class SubExpression : public SymbolExpression{
public:
SubExpression(Expression * left, Expression * right):SymbolExpression(left, right){}
int interpret(map<char, int> var) override
{
return left->interpret(var) - right->interpret(var);
}
};
Expression * analyse(string expStr){
stack<Expression * > expStack;
Expression * left = nullptr;
Expression * right = nullptr;
for(int i = 0; i < expStr.size(); i++){
switch(expStr[i]){
case '+':
left = expStack.top();
right = new VarExpression(expStr[++i]);
expStack.push(new AddExpression(left, right));
break;
case '-':
left = expStack.top();
right = new VarExpression(expStr[++i]);
expStack.push(new SubExpression(left, right));
break;
default:
expStack.push(new VarExpression(expStr[i]));
}
}
Expression * expression = expStack.top();
return expression;
}
int main()
{
cout << "Hello World!" << endl;
string expStr = "a+b-c+d";
map<char, int>var;
var['a'] = 5;
var['b'] = 2;
var['c'] = 1;
var['d'] = 6;
Expression * expression = analyse(expStr);
int result = expression->interpret(var);
cout<<result<<endl;
return 0;
}
转载自原文链接, 如需删除请联系管理员。
原文链接:Interpret,转载请注明来源!