首页 > 代码库 > Interpreter
Interpreter
#include <string>#include <iostream>#include <stack>using namespace std;stack<char> g_stack;class Context{public: void SetExpression(string sExpr) { m_sExpr = sExpr; } string GetExpression() const { return m_sExpr; }private: string m_sExpr;};class Interpreter{public: virtual void Translate(const Context& context)=0;};class ConcreteInterpreterA : public Interpreter{public: void Translate(const Context& context);};class ConcreteInterpreterB : public Interpreter{public: void Translate(const Context& context);};void ConcreteInterpreterA::Translate(const Context& context){ size_t len = context.GetExpression().size(); if (len == 0 || len % 2 != 0) { cerr<<"TranslateA failed! mismatch brackets"<<endl; } else { cout<<"TranslateA go through!"<<endl; }}void ConcreteInterpreterB::Translate(const Context& context){ while (!g_stack.empty()) g_stack.pop(); string sExpression = context.GetExpression(); for (unsigned int i = 0; i < sExpression.size(); i++) { if (sExpression[i] == ‘(‘) g_stack.push(sExpression[i]); else if (sExpression[i] == ‘)‘) { if (g_stack.size() == 0 || g_stack.top() != ‘(‘) { cerr<<"TranslateB failed! mismatch brackets"<<endl; return ; } else g_stack.pop(); } else { cout<<"TranslateB failed! invalid character in expression"<<endl; return ; } } if (g_stack.size() != 0) { cerr<<"TranslateB failed! mismatch brackets"<<endl; } else { cout<<"TranslateB go through!"<<endl; }}int main(int argc, char *argv[]){ Interpreter* pInterpreterA = NULL, *pInterpreterB = NULL; Context context; pInterpreterA = new ConcreteInterpreterA; pInterpreterB = new ConcreteInterpreterB; context.SetExpression(""); pInterpreterA->Translate(context); pInterpreterB->Translate(context); context.SetExpression("(()"); pInterpreterA->Translate(context); pInterpreterB->Translate(context); context.SetExpression("(())"); pInterpreterA->Translate(context); pInterpreterB->Translate(context); context.SetExpression("(())()"); pInterpreterA->Translate(context); pInterpreterB->Translate(context); delete pInterpreterA; delete pInterpreterB; return 0;}
Interpreter
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。