zoukankan      html  css  js  c++  java
  • const常量

    必须定义const常量的时候赋值

    #include <iostream>
    using namespace std;
    
    int main() {
        const int age = 10;
    
        age = 20;    //这里报错,不能改变
    
        getchar();
        return 0;
    }
    

    结构体声明与变量定义,加上const

    #include <iostream>
    using namespace std;
    
    struct Date {    //声明结构体
        int year;
        int month;
        int day;
    }
    
    int main() {
        const Date d = {2011, 2, 5};    //定义结构体变量,声明常量    
        d.year = 2015;    //这里报错,不能修改
        //struct Date d = {2011, 2, 5};    C语言需要加上关键词struct来定义
    
        getchar();
        return 0;
    }
    

    结构体赋值结构体

    #include <iostream>
    using namespace std;
    
    struct Date {    //声明结构体
        int year;
        int month;
        int day;
    }
    
    int main() {
        Date d = {2011, 1, 1};    //定义结构体变量
        Date d2 = {2013, 3, 3};
        d = d2;    //结构体赋值结构体
    
        getchar();
        return 0;
    }
    

    指针指向结构体,修改成员

    #include <iostream>
    using namespace std;
    
    struct Date {    //声明结构体
        int year;
        int month;
        int day;
    }
    
    int main() {
        Date d1 = {2011, 1, 1};    //定义结构体变量
        Date d2 = {2013, 3, 3};
        
        Date *p = &d1;    //指针指向结构体d1
        p->year = 2015;
        (*p).month = 5;
        *p = d2;
    
        cout << d1.year << endl;
    
        getchar();
        return 0;
    }
    

    指针;const只修饰右边的整体

    int * const p3 = &age;    //p3是常量;*p3不是常量,可以赋值
    *p3 = 20;    //age=20;
    p3 = &height;    //是常量,报错
    *p3 = 40;    //height=40;
    
  • 相关阅读:
    ES6 新属性 Symbol
    box-shadow 属性详解
    在vue 中 使用 tinymce编辑器
    var let const 结合作用域 的探讨
    防抖和节流在vue中的应用
    分享几个按钮样式
    队列学习
    栈的学习
    Object—常用的遍历
    从零认识Java Package
  • 原文地址:https://www.cnblogs.com/sec875/p/12256285.html
Copyright © 2011-2022 走看看