理解复杂的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 pstring cstrl =&s;

      pstring const cstr2 =&s;

     string *const cstr3 = &s;

把 const放在类型 pstring之后,然后从右向左阅读该声明语句就会非常清楚地知道 cstr2是 const psting 类型,即指向string对象的const指针。

不幸的的是,大多数在阅读C++程序时都习惯看到const放在类型前面。于是为了遵循惯例,只好建议编程时把const放在类型前面。但是,把声明语句重写为置 const于类型之后便与理解。

原文地址:https://www.cnblogs.com/canyuexingchen/p/2643485.html