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

8.5.9 constexpr函数

一个函数代表一种计算。有时我们希望在编译时进行某种计算,通常这么做的目的是为了避免在运行时计算同样的内容上百万次。使用函数可使计算更易理解,很自然地,有时我们希望在常量表达式中使用函数。在编译时对函数进行计算的想法可通过将函数声明为constexpr来实现。一个constexpr函数若给定常量表达式作为参数,则函数计算将在编译时完成。例如:

假设Point是一个简单的结构,包含两个成员x和y,表示一个二维坐标。现在,给scale()函数一个Point参数,它返回一个Point,其坐标为输入参数根据xscale和yscale缩放后的坐标。例如:

一个constexpr函数和普通函数行为相同,但若在需要一个常量的位置处使用它,则有所不同,此时若传递的参数是常量表达式(如p2情形),则计算在编译时完成,否则输出错误信息(如p1情形)。为使该机制可行,要求constexpr函数必须非常简单,使得编译器(每个符合规范的编译器)能计算它。在C++11中,要求constexpr函数体只能包含一条return语句(如scale()所示);在C++14中,还可以写简单的循环语句。一个constexpr函数不允许有副作用,即它不能改变函数体之外的变量值,当然待赋值或用于初始化的那些变量除外。 ...

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