代码改变世界

c++ const_cast操作符、指针常量和常量指针的解释

2008-11-26 21:40  Iron  阅读(288)  评论(0编辑  收藏  举报
#include <iostream>
using namespace std;
int main()
{
    //const_cast的用法
    {
    int a = 2;
    const int b = 3;
    //int *f = &b;
    int *c = const_cast<int*>(&b);//建立了b的临时变量
    *c = 6;//不能改变b的值
    int &d = a;
    d = 23;
    cout << &b << endl << c <<endl;
    cout << b << " " << *c << "*****" << a << " " << d <<endl;
    cout << &b << endl << c <<endl;

     int p = 20;

  const int *pp = &p;

  int *ppp = const_cast<int *>(pp);

  *ppp = 30;

  //*pp = 40;错误,但是可以通过PPP来改变pp的值
    cout << pp << endl << ppp << endl << &p;
  cout << *pp << p <<endl; //3030
    }
    //指针常量和常量指针
  {
      int a = 2;
      int b = 3;
      const int * c = &a;//常量指针,可改变指向地址的指针
      c = &b;//正确
      //*c = 5;不正确
      int * const d = &a;//指针常量,可改变指向变量值的指针
      *d = 5;//正确
      //d = &b;//不正确
  }
}