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

5.4.4 用户自定义字面值

类的一个目的是令程序员能设计、实现高度模仿内置类型的自定义类型。构造函数提供的初始化功能等同甚至超出了内置类型初始化的灵活性和效率,但对于内置类型,我们可以声明字面值:

·123是一个int。

·0xFF00u是一个unsigned int。

·123.456是一个double。

·"Surprise!"是一个const char[10]。

如果对用户自定义类型也能提供这种字面值就非常有用了。通过为恰当的字面值后缀定义含义,我们可以做到这一点,从而得到:

·"Surprise!"s是一个std::string。

·123s是second(秒)。

·12.7i是imaginary(虚部),因此12.7i+47是一个复数(即{47,12.7})。

特别是,通过使用合适的头文件和名字空间,我们就能直接从标准库获得上述功能。

不出意外,带有用户自定义后缀的字面值称为用户自定义字面值(user-defined literal)或简称为UDL。这种字面值是使用字面值运算符(literal operator)定义的。字面值运算符将其参数类型的字面值及一个后缀转换为其返回类型。例如,用于imaginary的后缀i可实现如下:

在这里,

·operator""指出我们在定义一个字面值运算符。 ...

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