给定一个语言,定义它的文法的一种表示,并定义一种解释器,这个解释器使用该表示来解释语言中的句子。
#include<iostream> #include<map> #include<string> #include<stack> class Expression { public: virtual int interpreter(std::map<char, int>) = 0; virtual ~Expression() {} }; class VarExpression :public Expression { public: VarExpression(const char& k) :key(k) {} int interpreter(std::map<char, int>var) override { return var[key]; } private: char key; }; class SymbolExpression :public Expression { public: SymbolExpression(Expression* l, Expression* r) :left(l), right(r) {} protected: Expression* left; Expression* right; }; class AddExpression : public SymbolExpression { public: AddExpression(Expression* left, Expression* right) :SymbolExpression(left, right) {} int interpreter(std::map<char, int> var) override { return left->interpreter(var) + right->interpreter(var); } }; class SubExpression :public SymbolExpression { public: SubExpression(Expression* left, Expression* right) :SymbolExpression(left, right) {} int interpreter(std::map<char, int> var) override { return left->interpreter(var) - right->interpreter(var); } }; class MulExpression :public SymbolExpression { public: MulExpression(Expression* left, Expression* right) :SymbolExpression(left, right) {} int interpreter(std::map<char, int> var) override { return left->interpreter(var) * right->interpreter(var); } }; class DivExpression :public SymbolExpression { public: DivExpression(Expression* left, Expression* right) :SymbolExpression(left, right) {} int interpreter(std::map<char, int> var) override { return left->interpreter(var) / right->interpreter(var); } }; Expression* analyse(std::string expStr) { std::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; case '*': // 乘法运算 left = expStack.top(); right = new VarExpression(expStr[++i]); expStack.push(new MulExpression(left, right)); break; case '/': // 除法运算 left = expStack.top(); right = new VarExpression(expStr[++i]); expStack.push(new DivExpression(left, right)); break; default: // 变量表达式 expStack.push(new VarExpression(expStr[i])); } } Expression* expression = expStack.top(); return expression; } void release(Expression* expression) { //释放表达式树的节点内存... } int main() { std::string expStr = "a+b-c+d-e*f/g"; std::map<char, int> var; var.insert(std::make_pair('a', 5)); var.insert(std::make_pair('b', 2)); var.insert(std::make_pair('c', 1)); var.insert(std::make_pair('d', 6)); var.insert(std::make_pair('e', 10)); var.insert(std::make_pair('f', 8)); var.insert(std::make_pair('g', 4)); Expression* expression = analyse(expStr); int result = expression->interpreter(var); std::cout << result << std::endl; release(expression); return 0; }