zoukankan      html  css  js  c++  java
  • C++_const

    //const在C不可以初始化数组

    //const在C++可以用来初始化数组

     1 #include <iostream>
     2 using namespace std;
     3 
     4 void main()
     5 {
     6     const int num = 5;
     7     int a[num];//const在C++可以用来初始化数组
     8     int i = 0;
     9 
    10     for (auto data : a)
    11     {
    12         data = i++;
    13         std::cout << data << std::endl;
    14     }
    15 
    16     system("pause");
    17 }

    常量和约束访问

    关键字const约束对象的访问性质,使对象值只能读,不能写,即不允许修改对象的值

    //C++权限问题与强类型

    //因为为了权限的编程,只读不可写的权限,指向常量的指针int const *p2(&b);C++强类型会忽略

    //给予可读可写的权限,常量指针int * const p4(&b);强类型发生作用

    //指向常量的常量指针const int * const p5(&a);给予只读权限

     1 #include <iostream>
     2 using namespace std;
     3 
     4 //C++权限问题与强类型
     5 //因为为了权限的编程,只读不可写的权限,指向常量的指针int const *p2(&b);C++强类型会忽略
     6 //给予可读可写的权限,常量指针int * const p4(&b);强类型发生作用
     7 //指向常量的常量指针const int * const p5(&a);给予只读权限
     8 
     9 void main()
    10 {
    11     int a = 10;
    12     const int b = 20;
    13 
    14     //指向常量的指针,指向的数据不可以赋值
    15     int const *p1(&a);
    16     int const *p2(&b);
    17 
    18     //常量指针
    19     int * const p3(&a);
    20     //int * const p4(&b);//error C2440: “初始化”: 无法从“const int *”转换为“int *”
    21     
    22     //指向常量的常量指针
    23     const int * const p5(&a);
    24     const int * const p6(&b);
    25     
    26     system("pause");
    27 }

    常引用

    const 类型&引用名=对象名;

    例如:

    int a=314;

    const int & ra=a;//ra是a的常引用

    cosnt比#define更有优势

    //#define强制替换,没有明确的类型

    //const动态监测类型,实现赋值,赋值会自动进行数据类型转换,避免类型不一致的出错

  • 相关阅读:
    2017.3.10组合数学学习——多重集合的排列、组合,有限概率
    poj 3169 Layout
    poj 1201 Intervals
    poj 1716 Integer Intervals
    2017.3.9 组合数学学习——组合、多重集排列
    [HNOI 2013]切糕
    思维相似处总结(未完待续)
    bzoj 3673: 可持久化并查集 by zky
    SDOI2013 森林
    标题还没想好
  • 原文地址:https://www.cnblogs.com/denggelin/p/5645501.html
Copyright © 2011-2022 走看看