返回介绍

3.7 A Postfix Writer

发布于 2025-02-24 22:44:37 字数 1888 浏览 0 评论 0 收藏 0

到目前为止我们还没有真正的决定 process() 将要真正做什么。如果我们想要发布一个表达式的后缀版,我们将要对 struct Type 增加一个字符串以便于显示出实际的操作符,且 process() 将要安排一个单独的被 tab 键缩进的行:

void process (const void * tree)
{
     putchar('/t');
     exec(tree, (* (struct Type **) tree) -> rank, 0);
     putchar('/n');
}

exec() 处理动态连接

static void exec (const void * tree, int rank, int par)
{
     assert(tree && * (struct Type **) tree
        && (* (struct Type **) tree) -> exec);

     (* (struct Type **) tree) -> exec(tree, rank, par);
}

每一个二元操作符被使用如下函数发出:

static void doBin(const void *tree)
{
  exec(((struct Bin *) tree) —> left);
  exec(((struct Bin *) tree) —> right);
  printf(" %s", (* (struct Type **) tree) —> name);
}

类型描述符如下绑定:

static struct Type _Add = { "+", mkBin, doBin, freeBin };
static struct Type _Sub = { "—", mkBin, doBin, freeBin };
const void * Add = & _Add;
const void * Sub = & _Sub;

应该很容易猜测一个数值是怎样被实现的。它被代表作为一个结构体携带 double 类型的信:

struct Val {
  const void * type;
  double value;
};
static void * mkVal (va_list ap)
{
  struct Val * node = malloc(sizeof(struct Val));
  assert(node);
  node —> value = va_arg(ap, double);
  return node;
}

处理组成的打印值:

static void doVal (const void * tree)
{
  printf(" %g", ((struct Val *) tree) —> value);
}

我们已经做了 - 没有子树要删除,因此我们可以使用库函数 free() 直接的删除值节点:

static struct Type _Value = { "", mkVal, doVal, free };
const void * Value = & _Value;

一元操作符如 Minus 将留作练习。

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文