const指针与指向const对象的指针

来源:互联网 发布:php 将数组分割成三段 编辑:程序博客网 时间:2024/05/14 14:04

原链接:http://blog.csdn.net/tobacco5648/article/details/8530975

1.const指针是一种指针,此指针指向的地址是不能够改变的,但是其指向的对象是可以被修改的,其定义类似:

    int* const p=地址;

    比如下面的代码:

[cpp] view plaincopy
  1. int b=12;  
  2. intconst a=&b;  
  3. void tes()  
  4. {  
  5.     *a=1;  
  6. }  
    此代码是正确的,先声明了变量b,然后声明一个const指针a,此指针指向变量b,在tes函数中修改指针a所指向的对象的值。

    如果将代码修改为:

    

[cpp] view plaincopy
  1. int b=12;  
  2. intconst a=&b;  
  3. void tes()  
  4. {  
  5.     int c=2;  
  6.     a=&c;  
  7. }  
    再编译就会出错:

t.cpp: In function 'void tes()':
t.cpp:6:5: error: assignment of read-only variable 'a'

因为指针a是const的,不能被重新赋值。

    2.指向const对象的指针,其指向的对象是const的,不能被修改,但是其本身并不是const的,可以修改其指向的地址。

    声明方式为:

    const int *p;

    

[cpp] view plaincopy
  1. const int* a;  
  2. void tes()  
  3. {  
  4.     int c=2;  
  5.     a=&c;  
  6. }  
    此代码是正确的,先声明了一个指向const对象的指针,然后在tes函数中将其指向c变量。

    

[cpp] view plaincopy
  1. const int* a;  
  2. void tes()  
  3. {  
  4.     int c=2;  
  5.     a=&c;  
  6.     *a=4;  
  7. }  
    此编码编译错误。

t.cpp: In function 'void tes()':
t.cpp:6:5: error: assignment of read-only location '* a'

    因为a所指向的对象是const的,不能修改。

版权声明:本文为博主原创文章,未经博主允许不得转载。

0 0
原创粉丝点击