c++ const 小结把const 变量理解成只读变量,比常量更合适. const作用域:局部. const 常用于头文件中,可能被多次包含.如果不是局部作用域,则会冲突. 一般编译时值就可确定,这时一般编译器不会为其分配变量空间,而直接使用其表示的常数值. 如果运行时确定,一旦确定就成为只读.
理解复杂的 const 类型的声明 阅读 const 声明语句产生的部分问题,源于 const 限定符既可以放在类型前也可以放在类型后,: string const s1; // s1 and s2 have same type, const string s2; // they're both strings that are const 用 typedef 写 const 类型定义时,const 限定符加在类型名前面容 易引起对所定义的真正类型的误解:
string s; typedef string *pstring;
const string * str; 注意这里const 限定的是string. 相当于(const string) * str; 而const pstring cstr1,相当于 const (string *) cstr1; const pstring cstr1 = &s; // written this way the type is obscured pstring const cstr2 = &s; // all three decreations are the same type string *const cstr3 = &s; // they're all const pointers to string
|
|