Skip to Content
C++语言导学(原书第2版)
book

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

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
5h 35m
Chinese
Pearson
Content preview from C++语言导学(原书第2版)

3.6 函数参数和返回值

函数调用是从程序的一个部分向另一个部分传递信息的主要方式,也是推荐方式。执行任务所需的信息作为参数传递给函数,生成的结果作为返回值传回。例如:

函数间也存在其他传递信息的路径,例如全局变量(参见1.5节)、指针和引用参数(参见3.6.1节),以及类对象中的共享状态(参见第4章)。全局变量是众所周知的错误之源,我们强烈建议不要使用它,而状态通常只应在共同实现了一个良好定义的抽象的函数间共享(例如,类的成员函数,参见2.3节)。

了解了函数传递信息的重要性,就不会对存在多种传递方式感到惊讶了。其中的重点是:

·对象是拷贝的还是共享的?

·如果共享对象,它可变吗?

·对象可以移动从而留下一个“空对象”吗(参见5.2.2节)?

参数传递和返回值的默认行为是“拷贝”(参见1.9节),但某些拷贝可隐式优化为移动。

在sum()例子中,得到的int被拷贝出sum()而将可能非常大的vector拷贝进sum()会很低效且无意义,因此参数是以引用方式传递的(用&指出,参见1.7节)。

sum()没有理由修改其实参。这种不可变性是通过将vector参数声明为const实现的(参见1.6节),因此vector是以const引用方式传递的。

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

软件开发实践:项目驱动式的Java开发指南

软件开发实践:项目驱动式的Java开发指南

Raoul-Gabriel Urma, Richard Warburton
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python机器学习案例精解

Python机器学习案例精解

Posts & Telecom Press, Yuxi (Hayden) Liu

Publisher Resources

ISBN: 9787111633280