• 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动态监测类型,实现赋值,赋值会自动进行数据类型转换,避免类型不一致的出错

  • 相关阅读:
    json字符串数组判断其中
    json字符串数组判断其中
    jquery select chosen禁用某一项option
    数据库培训知识
    人员管理模块代码总结2015/8/12整理
    正则表达式在STARLIMS中的应用总结
    控件属性表
    Form-公共代码
    Server-Script公共代码
    Celient-Script公共代码
  • 原文地址:https://www.cnblogs.com/denggelin/p/5645501.html
Copyright © 2020-2023  润新知