常量

定义方式有3种.

字面量

二进制字面量

#include <bitset>

unsigned mask = 0b111000000;  // C++14
cout << bitset<9>(mask) << endl;  // 需要手动指定二进制位数

自定义字面量

C++11 引入了自定义字面量,可以使用 operator"" 后缀 来将用户提供的字面量转换成实际的类型。C++14 则在标准库中加入了不少标准字面量。如以下两种写法

#include <thread>

using namespace std::chrono;

auto a = "hello"s;  // a 是string
auto b = 500ms;

如果是自定义,则后续需要以 _ 打头,如下所示

length operator"" _m(long double v){
	return length(v, length::metre);
}

length operator"" _cm(long double v){
	return length(v, length::centimetre);
}

数字分隔符

C++14 开始,允许在数字型字面量中任意添加 ' 来使其更可读。

unsigned mask = 0b111'000'000;
long r_earth_equatorial = 6'378'137;
double pi = 3.14159'26535'89793;
const unsigned magic = 0x44'42'47'4E;