看个小例子
const int *p;与int * const p
这两个声明的中文名称常常搞得混乱不堪。
第一个声明的const是声明说明符,它修饰p所指向的对象,但p仍然是可变的,这意味着p是一个指向常量的指针,简称常量指针。
第二个声明的const是声明符的一部分,它修饰的对象是p,这意味着p是一个常量,而且是一个指针类型的常量,简称指针常量。指针常量又常常被人称为“常指针”或“常指针变量”
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- const int *p;
- int i=10;
- p=i;//ok
- *p=11;//error
- system("pause");
- return 0;
- }
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- int i=10;
- int * const p=&i; //p为const所修饰,所以必须在定义时初始化
- *p=11;//ok
- cout<<*p<<endl;
- system("pause");
- return 0;
- }