const
1 minute read
Const限定符
const int maxn = 512;
maxn = 512;//error, not allowed
const必须被初始化
const int i = get_size();//initialized while running
const int j = 42;
const int k;//error
默认状态下,const对象仅在文件内有效
使用 extern
可以在一个文件中定义 const
并在多个其他文件中声明并使用它们。
//in file_1.cc
extern const int maxn = 512;
//in file_1/h
extern const int maxn;//与 file_1.cc 中定义的 maxn 是同一个
//此处声明表示 maxn 的定义将在别处出现
初始化和对const的引用
进行类型转换时,引用类型 &ri 会被绑定一个 临时量(temporary),
double dval = 3.14;
const int &ri = dval;//error
指针与const
顶层const与底层const
顶层 const (top-level const) 表示指针本身是个常量 底层 const (low-level const) 表示指针所指的对象是一个常量
int i = 0;
int *const p1 = &i; //不能改变 p1 的值,这是一个顶层 const
const int ci = 42; //不能改变 ci 的值,这是一个顶层 const
const int *p2 = &ci; //允许改变 p2 的值,这是一个底层 const
const int *const p3 = p2; //靠右的 const 是顶层 const,
//靠左的是底层 const
const int &r = ci; //用于声明引用的 const 都是底层 const
进行对象的拷贝操作时,顶层 const 几乎不受影响,底层 const 的限制不能忽视
constexpr 常量
c++11规定,允许将变量声明为 constexpr
类型以便由编译器来验证变量的值是否是一个常量表达式。
声明为 constexpr
的变量一定为一个常量,并且允许使用常量表达式初始化
constexpr int mf = 20;
constexpr int limit = mf +1;
constexpr int sz = size(); //只有当 size() 是一个 constexpr 函数时才是一条正确的语句