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;
    
  • 相关阅读:
    【转】Redis和Memcache对比及选择
    Ubuntu下php环境的搭建
    【HTML和CSS】总结
    【python】 The different between ' %r ' and ' %s '
    Learn Python The Hard Way
    Vim 插件配置及快捷键
    sublime-text 插件配置
    mysql-5.7在CentOS-7下的rpm安装
    oracle pdb基本管理
    Oracle 12cR2 Installation On CentOS-7
  • 原文地址:https://www.cnblogs.com/sec875/p/12256285.html
Copyright © 2011-2022 走看看