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

 

原文链接: https://www.cnblogs.com/yuhl/archive/2012/11/19/2777547.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    c++ const 小结

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/69945

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午2:02
下一篇 2023年2月9日 下午2:03

相关推荐