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.2 类型错误

一旦语法错误被排除后,编译器就会开始检查类型错误:它将会检查你所声明的变量和函数的类型(或者发现你忘记了声明类型);检查赋予变量或函数的数值或表达式的类型以及传递给函数参数的数值或表达式的类型。例如:

让我们仔细分析一下这些错误:

1.对于arena(7),我们将area错写为arena。因此编译器认为我们是要调用函数arena。(编译器还有其他“想法”吗?这就是前文所说的,编译器是不知道你想做什么的。)假设没有函数arena(),你会得到未定义函数的错误信息。如果存在函数arena()并且这个函数能够接受7作为输入参数的话,你会遇到一个更大的麻烦:程序将会被正确编译,但是它不会按照你预想的那样去运行(这是一个逻辑错误,详见5.7节)。

2.对于area(7),编译器检查到错误是参数个数不匹配。对于C++语言,函数调用必须使用正确的参数个数、参数类型和顺序。在合理使用类型检查系统时候,它可以作为实时的错误检查工具(详见19.1节)。

3.对于area("seven",2),你可能期望编译器能够识别出"seven"表示的是数字7。但它做不到这点。当一个函数需要输入一个整数的时候,我们不能给它一个字符串。C++确实支持一些隐含的类型转换(见3.9节),但不包括string到int的转换。编译器不会试图去猜测你所要表示的含义。不然,你认为area("Hovel lane",2),area("7,2")和area("sieben","zwei")表示什么含义呢?

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