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版)

5.3.1 语法错误

如果我们按照如下方式调用area(),会有什么结果呢:

上面每一行程序都有一个语法错误,即它们不符合C++语言的语法规范,因此编译器会拒绝它们。不幸的是,对你,即程序员来说,理解语法错误的报告信息往往不是那么容易。为了确定错误,编译器往往会读取更多的信息。这会导致即使是一个小错误(往往在发现这个错误时,你会觉得不可思议,自己怎么会犯这种低级错误),编译器也会报告很多繁杂信息,甚至会指向程序中的其他行。因此,如果你在编译器所指向的错误行中没有发现错误的话,还应该检查一下前几行程序是否有错。

需要注意的是,编译器并不知道你想做什么。它只会报告你所做的是否有错,而不会报告你想做的是否有错。例如,在上面的例子中,s3的声明有错,但是编译器不会告诉你:

“你拼错了int,i不要大写”

而是报告如下信息:

“语法错误:变量s3前丢失';'”

“s3没有存储类型或数据类型”

“Int没有存储类型或数据类型”

在你习惯并理解这些信息含义前,这些信息是很令人费解的。对于同一代码,不同的编译器可能会给出不同的错误信息。幸运的是,你会很快习惯理解这些信息的。实际上,上面这些令人费解的信息可以被解释为:

“在s3前有一个语法错误,需要检查一下Int或者s3的数据类型”

实际上,发现这些问题并不是一件很困难的事。

试一试

尝试编译一下上面的例子,看看编译器的返回信息是什么。

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