constcpp

  1 /*constCCPP*/
  2 
  3 // c语言
  4 void main()
  5 {
  6     const int num =5;
  7     int a[num];// 不可以
  8     int *p = #
  9     *p = 3;// c语言是弱类型语言
 10     printf("%d",num);
 11 }
 12 
 13 
 14 
 15 //----------------------------------------------------
 16 
 17 // C++中
 18 
 19 void main()
 20 {
 21     const int num =5;
 22     int a[num];// 可以,constC++ 内部可以用初始化数组
 23     
 24     int i = 0;
 25     for(auto data : a)
 26     {
 27         data = i++;
 28         std::cout << data << std::endl;
 29     }
 30 }
 31 
 32 //----------------------------------------------------
 33 
 34 void main()
 35 {
 36     const int num =5;
 37     int *p =(int *) &num;// C语言的强制转换
 38     *p = 4;// C++ 不会执行这行代码  
 39     std::cout << num << std::endl;// 输出5
 40 }
 41 
 42 /-----------------------------------------------------
 43 
 44 // C++ 一旦const,就无法操作
 45 void main()
 46 {
 47     const int num =5;
 48     int *p = const_cast<int *>(&num);// 强制去掉const属性
 49     *p = 4;  // 可以编译通过  但是禁止执行
 50     std::cout << num << std::endl;// 输出5
 51 }
 52 
 53 //----------------------------------------------------
 54 
 55 void main()
 56 {
 57     int a = 10;
 58     const int b = 20;
 59     int const *p1(&a);// C++用于限定权限指向常量的指针变量不会严格检查
 60     const int *p2(&b);// p1,p2 指向常量的指针,指向的数据不可以赋值
 61 
 62 
 63     int *const p3(&a);// 指向变量的常量指针
 64     int * const p4(&b);// 类型不匹配
 65 
 66     const int * const p5(&a);// 限定权限
 67     const int * const p6(&b);
 68 }
 69 
 70 // C++ 权限问题与类型
 71 
 72 // 因为为了权限的编程  只读不可写的权限 int const *p1,  C++强类型会忽略
 73 
 74 // 给予可读可写的权限,不可以跳到别人的地址读写别人的钱,int * const p 如果给的是const int /类型  此时强类型会发生作用
 75 
 76 // const int * const p; 给予只读的权限,不能跳到别人的地址
 77 
 78 //----------------------------------------------------
 79 
 80 /*常引用*/
 81 
 82 void main()
 83 {
 84     const int num = 100;
 85     const int & rnum = num;
 86     std::cout << &num << &rnum << std::endl;
 87 }
 88 
 89 //----------------------------------------------------
 90 
 91 int select(const int & rnum)// 加const 防止修改
 92 {
 93     //rnum = rnum - 0.02;
 94     return rnum;
 95 }
 96 
 97 void main()
 98 {
 99     const int num1 = 100;
100     int num2 = 200;
101     std::cout << select(num1) << std::endl;// 100
102 }

 

 

posted on 2015-05-27 11:14  Dragon-wuxl  阅读(89)  评论(0)    收藏  举报

导航