定义方式有3种.
define
: 在预编译期进行处理
const
: 可以放在 namespace 中, 但是可以通过 去常量引用 来将容器常量转换为可修改变量, 即失去了const修饰效果
using std::string;
const string name = "abcd";
string& alias = const_cast<string&>(name);
alias[0] = 'p';
constexpr
: 常量表达式.
#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;