Skip to Content
C++程序设计:原理与实践(基础篇)(原书第2版)
book

C++程序设计:原理与实践(基础篇)(原书第2版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
9h 36m
Chinese
Pearson
Content preview from C++程序设计:原理与实践(基础篇)(原书第2版)

6.5.1 实现文法规则

我们在计算器程序的设计中使用了四个函数,一个函数用于读入单词,其他三个函数分别实现文法的三条规则:

注意:每个函数只处理表达式的一个特定部分,将其他工作留给其他函数,这样可以简化函数的实现。如同每个人处理自己所擅长的问题,将其他不熟悉的问题留给同事完成一样。

这些函数应该具体做什么呢?每个函数应该根据其所实现的文法规则,调用其他文法函数,并利用get_token()获得规则所需要的单词。例如,当primary()函数实现“(Expression)”规则时,它必须调用

这些语法分析函数的返回值又应该是什么呢?这个问题实际等价于——我们想得到什么结果呢?例如,对于2+3,expression()应该返回5。毕竟,所有信息都包含其中了。这就是我们应该做的!这样做实际上回答了前面列表中最复杂的问题:“如何表示45+5/7才有利于计算它的值?”我们在读入表达式时就计算它的值,而不是把它的某种表示形式存储到内存中。这个小小的想法其实是一个重要的突破!我们如果让expression()返回某种复杂的形式,随后再进行计算的话,程序规模会是直接计算值的版本的4倍。直接计算表达式的值会节省我们80%左右的工作量。

剩下的那个函数是get_token():由于它只处理单词,而不是表达式,因此它不能返回一个子表达式的值。例如,“+”和“(”不是表达式。因此,它必须返回一个Token对象。因此有: ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

C++语言导学(原书第2版)

C++语言导学(原书第2版)

本贾尼 斯特劳斯特鲁普
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano

Publisher Resources

ISBN: 9787111562252