const和指针

1.指向const对象的指针 const int *p; 或者 int const *p; c++规定,const关键字放在类型或变量名之前是等价的. 2.const指针 int c=20; int *const p4=&c; 指针p4称为const指针。它和指向const对象的指针恰好相反,它不能够修改所指向对象,但却能够修改指向对象的数值。另外,这种指针在声明时必须初始化。 3.指向const对象的const指针 const int d=30; const int *const dp=&d; 指针dp既不能修改指向的对象,也不能修改指向对象的值。
#include <iostream>
 2 
 3 using namespace std;
 4 
 5 int main(int argc, char *argv[])
 6 {
 7     int a=3;
 8     int b;
 9     
10     /*定义指向const的指针(指针指向的内容不能被修改)*/ 
11     const int* p1; 
12     int const* p2; 
13     
14     /*定义const指针(由于指针本身的值不能改变所以必须得初始化)*/ 
15     int* const p3=&a; 
16     
17     /*指针本身和它指向的内容都是不能被改变的所以也得初始化*/
18     const int* const p4=&a;
19     int const* const p5=&b; 
20     
21      p1=p2=&a; //正确
22      *p1=*p2=8; //不正确(指针指向的内容不能被修改)
23     
24      *p3=5; //正确
25      p3=p1; //不正确(指针本身的值不能改变) 
26     
27      p4=p5;//不正确 (指针本身和它指向的内容都是不能被改变) 
28      *p4=*p5=4; //不正确(指针本身和它指向的内容都是不能被改变) 
29      
30     return 0; 
31 }
参考: [1].  http://www.cnblogs.com/younes/archive/2009/12/02/1615348.html [2].  http://www.cnblogs.com/hustcat/archive/2009/04/11/1433549.html

你可能感兴趣的:(指针,Const)