#include <iostream>
#include <map>
#include <string>
using namespace std;
class Context
{
private:
map<string, int> valueMap;
public:
void addValue(string key,int value)
{
valueMap.insert(std::pair<string,int>(key,value));
}
int getValue(string key)
{
return valueMap[key];
}
};
class AbstractExpression
{
public :
virtual int interpreter(Context context) = 0;
};
class AddNonterminalExpression : public AbstractExpression
{
private :
AbstractExpression *left;
AbstractExpression *right;
public:
AddNonterminalexpression_r(AbstractExpression *left, AbstractExpression *right)
{
this->left = left;
this->right = right;
}
int interpreter(Context context)
{
return this->left->interpreter(context) + this->right->interpreter(context);
}
};
class SubtractNonterminalExpression : public AbstractExpression
{
private :
AbstractExpression *left;
AbstractExpression *right;
public:
SubtractNonterminalexpression_r(AbstractExpression *left, AbstractExpression *right)
{
this->left = left;
this->right = right;
}
int interpreter(Context context)
{
return this->left->interpreter(context) - this->right->interpreter(context);
}
};
class TerminalExpression : public AbstractExpression
{
private :
int i;
public :
Terminalexpression_r(int i)
{
this->i = i;
}
int interpreter(Context context)
{
return this->i;
}
};
int main(){
//a-b+c
Context context;
context.addValue("a", 7);
context.addValue("b", 8);
context.addValue("c", 2);
SubtractNonterminalExpression *subtractValue = new SubtractNonterminalexpression_r(new Terminalexpression_r(
context.getValue("a")), new Terminalexpression_r(context.getValue("b")));
AddNonterminalExpression *addValue = new AddNonterminalexpression_r(subtractValue, new Terminalexpression_r(
context.getValue("c")));
cout<< addValue->interpreter(context);
system("pause");
return 0;
}
![c++ 解释器模式 - 1307520486 - 1307520486的博客 c++ 解释器模式 - 1307520486 - 1307520486的博客](https://i-blog.csdnimg.cn/blog_migrate/cce544e7261bf3a4535656c82b969b03.png)
![c++ 解释器模式 - 1307520486 - 1307520486的博客 c++ 解释器模式 - 1307520486 - 1307520486的博客](https://i-blog.csdnimg.cn/blog_migrate/cce544e7261bf3a4535656c82b969b03.png)