const之常用方法总结

1. const对象

      定义一常量避免被无意修改,定义时必须被初始化;
      const int temp = 512;
temp = 0; // error:attempt to write to const object

2. const引用

      定义一个指向const对象的引用,可读取但不可以修改;

     

      const int temp = 512;

      const int &rtemp = temp;

      int &rtemp2 = temp; // error:nonconst regerence to const object


 

3. const作用域

      全局作用域定义的const变量是定义该对象的文件的局部变量,不可被其它文件访问,但通过指定为extern则可以在整个程序中访问const对象。

 

      对比:

      // file1.cpp

      int one = 10;

      extern const int two = 20;

      // file2.cpp

      extern int one;

      extern const int two;

 

      注意:如果const变量不是用常量表达式初始化,不应该在头文件不定义。     

 


 

4. const指针 & 指向const对象的指针

      const指针:指针本身不可以修改,但指向的值可修改。

      指向const对象的指针:不允许用指针修改所指向的值,指针本身可修改(指向另一个const对象)。

     

      对比:

      // const指针

      int numb = 20;

      int *const one = &numb;

      one = one; // error:one is const

      *one = 0; // ok

      // 指向const对象的指针

      const double *one;

      *one = 10; // error:*one might be const

      const double pi = 3.14;

      double *ptr = π // error:ptr is a plain pointer

      const double *cptr = π // ok

 


 

5. 指向const对象的const指针

      即不能修改所指对象的值,也不能修改该指针的指向。

     

      const double pi = 3.14;

      const double *const pi_ptr = π


 

6. const对象的动态数组

      数组元素都是const对象,无法重新赋值。

    

      const int *array = new const int[100](); // ok:value-initialized


 

7. const_cast的使用

      可转换掉表达式的const性质,除了添加或删除const特性,用const_cast符来执行其它任何类型转换都会引起编译错误。

     

      const char *par;

      char *pc = string_copy(const_cast<char*>(par));


 

8. const参数

      const引用避免复制。

      bool Shorter(const string &s1, const string &s2);

      int Greater(const void* p1, const void* p2);

 

      返回值为const:返回值不能被修改,当然也不能为左值。

      const char &Get(int n);

 

      const函数。

      void Get(int n) const;

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值