DesignPatterns/c++/interpreter.cc
2025-07-10 22:26:33 +08:00

41 lines
835 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @name 解释器模式
* @brief: 定义语言的语法表示
* @note 场景SQL解析、正则表达式、数学公式计算
*/
class Expression {
public:
virtual int interpret() = 0;
};
class Number : public Expression {
public:
Number(int value) : value(value) {}
int interpret() override { return value; }
private:
int value;
};
class Add : public Expression {
public:
Add(Expression* left, Expression* right)
: left(left), right(right) {}
int interpret() override {
return left->interpret() + right->interpret();
}
private:
Expression* left;
Expression* right;
};
// 使用:构建表达式树 (2 + (3 + 4))
Expression* expr = new Add(
new Number(2),
new Add(new Number(3), new Number(4))
);
int main()
{
int result = expr->interpret(); // 输出9
}