const主要是为了程序的健壮型,减少程序出错.
最基本的用法:

  1. const int a=100; b的内容不变,b只能是100也就是声明一个int类型的常量(#define b =100)
  2. int const b=100; //和上面作用一样

const指针和引用一般用在函数的参数中

  1. int* m = &a; //出错,常量只能用常指针
  2. int c= 1;const int*pc = &c;//常指针可指向常量
  1. const int* pa = &a; //指针指向的内容为常量(就是b的值不变)
  2. int const *a = &b; //指针指向的内容为常量(就是b的值不变)*p=3//error
  3. int* const a = &b; //指针为常量,不能更改指针了如 a++但可以改值*p=3;

从这可以看出const放在*左侧修饰的是指针的内容,const放在*右侧修饰的是指针
本身. 
const引用的用法和指针一样

  1. int const & a=b; 和指针一样
  2. const int& a=b; 和指针一样

但没有 int& const a=b 的用法因为引用不能做移位运算,但只是出个warning

const int* const a = &b; //综合应用,一般用来传递多维的数组
类如:char* init[] = {"Paris","in the","Spring"};
void fun(const int* const a){}
fun(init)//保护参数不被修改

  1. int A(int)const; //是常函数,只能用在类中,调用它的对象不能改改变成员值
  2. const int A(); //返回的是常量,所以必须这么调用 const int a=A();
  3. int A(const int); //参数不能改值,可用在任意函数
  4. int A(const int*);
  5. ....
  6. int height() const;//常函数只能由常函数调用
  7. int max(int,int) const;
  8. int Max = max(height(),height());
  1. const int* pHeap = new int;
  2. delete pHeap;
  3. p = NULL;//出错

我的解决办法是强制类型转换

  1. const int* pHeap = new int(1);
  2. delete (int*)pHeap;
  3. pHeap = NULL;

一、const 和引用联合使用的时候要注意

  1. const int a = 1;
  2. const int& ref1 = a;
  3. const int& ref2 = 1;

ref1 和 ref2 都是正确的,但是他们引用的内容和一般的引用不同
对 const int& ref1 = a; 而言,其实这个 ref1 已经和 a 没有任何关系了
ref1 实际上是对一个临时量的引用。同理 const int& ref2 = 1; 也是对
一个临时量做的引用。当引用临时量是 C++ 的隐式类型转换可以起作用。
临时量的生存期和引用量的生存期相同。

二、强传const对象可能导致无定义行为

对于优化做的比较好的编译器,代码 const int i = 1;
当后面用到变量 i 的时候,编译器会优化掉对 i 的存取,而直接使用立即数 1

const int i = 1;

*(const_cast<int*>(&i)) = 2;
cout << *(int*)&i << endl;
cout << i << endl;

所以,对 const 对象做 const_cast 可能导致无定义行为
目前我就遇到这些问题,那位还有补充的吗

有哪些不对的地方,请大家指正。求交流。。。

最新文章

  1. 【转】logback logback.xml常用配置详解(一)&lt;configuration&gt; and &lt;logger&gt;
  2. python学习笔记3(元组、字典)
  3. Python学习笔记04
  4. nginx location配置
  5. 【applicationContext.xml】配置文件找不到
  6. java1.8的几大新特性(一)
  7. HashMap通过value反查key
  8. 苹果新政,禁止开发者在App中加入检查更新功能
  9. 学习日记-----ORM
  10. C#遍历文件名
  11. MVC+Front Controller
  12. 解决adb command not found以及sdk环境配置
  13. mybatis入门系列二之输入与输出参数
  14. leetcode — valid-number
  15. 使用IIS调试ASP.NET网站程序
  16. BZOJ3324 : [Scoi2013]火柴棍数字
  17. 【xsy1303】生成树 乱搞
  18. 基于jQuery实现的Ajax 验证用户名唯一性
  19. RestTemplate请求https忽略证书认证
  20. Arduino学习笔记A6(补充) - 在串口读取多个字符串,并且转换为数字数组

热门文章

  1. 东芝笔记本Satellite M40-A
  2. RHEL6安装Oracle 11g R2
  3. 基数排序算法-python实现
  4. CI 框架怎么去掉隐藏入口文件 index.php
  5. genmotion 安装 app 报错 This application is&#39;t compatible with your mobile phone解决办法
  6. Office 2016激活教程(附KMS激活软件)
  7. 关于在github上 下载源码 clone 非 master 分支的代码
  8. jdbc练习demo
  9. Django ORM-02
  10. vconsole使用