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

9.1 用户自定义类型

C++语言提供了一些内置类型,如char、int和double(附录A.8)。对于一个类型,如果编译器无须借助程序员在源码中提供的任何声明,就知道如何表示这种类型的对象以及可以对它进行什么样的运算(例如+和*),那么我们就称这种类型是内置的(built-in)。

非内置的类型称为用户自定义类型(User-Defined Type,UDT)。用户自定义类型包括每个ISO标准C++实现都提供给程序员的标准库类型,如string、vector和ostream(参见第10章),也可以是我们为自己创建的类型,如Token和Token_stream(参见6.5节和6.6节)。一旦掌握了足够多的必要的语言功能,我们就可以创建图形类型,如Shape、Line和Text(参见第18章)。标准库类型很大程度上可以和内置类型一样看作语言的一部分,但我们还是将它们看作用户自定义类型,因为它们和我们自己创建的类型使用了同样的语言功能和技术;标准库的开发者并没有什么特权或者语言工具是你我所不具备的。与内置类型相似,大多数用户自定义类型支持一些运算。例如,vector有[]和size()运算(参见4.6.1节和附录C.4.8),ostream有<<,Token_stream有get()(参见6.8节),Shape有add(Point)和set_color()(参见19.2节)。

我们为什么要创建自定义类型呢?原因在于编译器不知道我们想在程序中使用的所有类型。它也不可能知道,因为有用的类型实在太多了——没有语言设计者或者编译器开发者能预知所有类型。我们每天都创建新的类型。为什么?类型又有什么用?通过类型,我们可以用代码直接、有效地表达我们的思想。当我们编写代码时,理想情况就是能在代码中直接表达思想,这样我们自己、同事以及编译器就能理解代码的含义。当我们想进行算术运算时,int类型会起到很大作用;当我们想处理文本时,string类型会带来很大帮助;当我们想处理计算器的输入时,Token和Token_stream会起到很大作用。这些类型带来的帮助体现在两个方面: ...

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