const与指针

来源:互联网 发布:mac如何设置睡眠时间 编辑:程序博客网 时间:2024/06/15 06:18

看个小例子

const int *p;与int * const p

这两个声明的中文名称常常搞得混乱不堪。

第一个声明的const是声明说明符,它修饰p所指向的对象,但p仍然是可变的,这意味着p是一个指向常量的指针,简称常量指针。

第二个声明的const是声明符的一部分,它修饰的对象是p,这意味着p是一个常量,而且是一个指针类型的常量,简称指针常量。指针常量又常常被人称为“常指针”或“常指针变量”

 

  1. #include "stdafx.h"
  2. #include <iostream>
  3. using namespace std;
  4. int _tmain(int argc, _TCHAR* argv[])
  5. {
  6.     const int *p;
  7.     int i=10;
  8.     p=i;//ok
  9.     *p=11;//error
  10.     system("pause");
  11.     return 0;
  12. }
  1. #include "stdafx.h"
  2. #include <iostream>
  3. using namespace std;
  4. int _tmain(int argc, _TCHAR* argv[])
  5. {
  6.     int i=10;
  7.     int * const p=&i; //p为const所修饰,所以必须在定义时初始化
  8.     *p=11;//ok
  9.     cout<<*p<<endl;
  10.     system("pause");
  11.     return 0;
  12. }
原创粉丝点击