【C++ Primer学习笔记1】const 小结

来源:互联网 发布:苏州网页美工培训 编辑:程序博客网 时间:2024/06/03 23:03

1const int i = 5在编译时编译器如define方法处理,若需要作用于其他文件应加extern改为externconst int

 

2reference to const : const int &rtoc= const int odata

 

   int i = 40;

   const int &r1 = i;      //允许将const int&绑定在一个普通int

   const int &r2 = 40 * 2;//同样合法,40字面值为int

   int &r3 = r1;           //错误

 

3、常量引用可能引用一个非常量的值(参数列表)

 

4pointer to const

 

   const double pi = 3.14D;

   double p* = π        //Wrong!

   const double *cp = π //Right

   double dval = 3.14;

   cp = &dval;             //Right

 

5const pointer

 

   int i = 10;

   int *const curi = &i;

  

   const double pi = 3.14159;

   const double *const pip = π//constpointer to const常量常指针

 

6top-level const and low-level const

  

   top-level const : object is a const(class orobject or pointer);

   low-level const : pointer or reference tosth;

  

  执行拷贝或赋值操作时须有相同的底层const资格

 

   int i = 0;

   int *const p1 = &i;    //top

   const int ci = 40;     //top

   const int *p2 = &ci;   //low

 

7、指针、常量和类型别名

 

   typedef char *pstring;

   const pstring cstr = 0; // const pointer tochar

   const pstring *ps;      // pointer to const pointer to char

  其中typedef不能理解为填充替换含义,pstring的基本数据类型是指针 , char*的基本数据类型为char

   const pstring cstr = 0;//指向charconst pointer

   const char *cstr = 0;  //指向const charpointer

0 0
原创粉丝点击