当前位置: 首页 > article >正文

C++ 设计模式-解释器模式

数学表达式解释器

示例需求

  1. 支持数字、变量、加减乘除运算
  2. 支持函数调用(如 max(2,3)
  3. 能够处理嵌套表达式(如 (x + 5) * max(y,10)

完整代码实现

#include <iostream>
#include <memory>
#include <unordered_map>
#include <vector>
#include <sstream>
#include <cctype>
#include <cmath>

// ====================== 解释器核心组件 ======================
class Context {
   
public:
    std::unordered_map<std::string, double> variables;
    double getVariable(const std::string& name) const {
   
        auto it = variables.find(name);
        if (it == variables.end()) throw std::runtime_error("Undefined variable: " + name);
        return it->second;
    }
};

class Expression {
   
public:
    virtual double interpret(const Context& ctx) const = 0;
    virtual ~Expression() = default;
};

// ====================== 终结符表达式 ======================
class Number : public Expression {
   
    double value;
public:
    Number(double v) : value(v) {
   }
    double interpret(const Context&) const override {
    return value; }
};

class Variable : public Expression {
   
    std::string name;
public:
    Variable(std::string n) : name(std::move(n)) {
   }
    double interpret(const Context& ctx) const override {
   
        return ctx.getVariable(name);
    }
};

// ====================== 非终结符表达式 ======================
class AddExpr : public Expression {
   
    std::unique_ptr<Expression> left, right;
public:
    AddExpr(Expression* l, Expression* r) : left(l), right(r) {
   }
    double interpret(const Context& ctx) const override {
   
        return left->interpret(ctx) + right->interpret(ctx);
    }
};

class MultiplyExpr : public Expression {
   
    std::unique_ptr<Expression> left, right;
public:
    MultiplyExpr(Expression

http://www.kler.cn/a/559192.html

相关文章:

  • 跟着 Lua 5.1 官方参考文档学习 Lua (5)
  • 论文解读(全头皮重建方向):3DCMM
  • Baklib知识中台架构迭代与服务效能升级
  • 云计算中的API网关是什么?为什么它很重要?
  • 【蓝桥杯单片机】第十三届省赛第二场
  • 【落羽的落羽 数据结构篇】顺序结构的二叉树——堆
  • DAY11 Tensorflow 鸢尾花数据集可视化训练
  • MobaXterm_Portable_v23.2 免费下载与使用教程(附安卓替代方案)
  • Java中的自然语言处理(NLP)工具:Stanford NLP、Apache OpenNLP、DL4J
  • 萌新学 Python 之 lambda 函数
  • 财务运营域——营收稽核系统设计
  • springcloud gateway并发量多大
  • 蓝桥杯训练 补题
  • 2025年微店平台商品详情接口调用指南(Python代码示例)
  • [LeetCode力扣hot100]-快速选择和快排
  • DeepSeek各模型现有版本对比分析
  • 深入解析 Spring WebFlux:原理与应用
  • 2025年SCI一区智能优化算法:混沌进化优化算法(Chaotic Evolution Optimization, CEO),提供MATLAB代码
  • 下载CentOS 10
  • Debian系统终端输入ifconfig报错