zoukankan      html  css  js  c++  java
  • c++ const 类

    01_const_class.cpp

    #include<iostream>
    using namespace std;
    
    struct A{
        int m;
        int n;
        A(){}
        A(int a,int b){m=a;n=b;}
        ~A(){}
    };
    
    int main()
    {
        const int a=10;
    //err:  a =200;
        // 如果类类型对象是只读的,其内部成员不是const,那么可以采用普通构造函数赋值
        const A b(10,20);
    //  b.m =20;
    //  b.n =200;
    
        return 0;
    }
    

    02_const_class_member.cpp

    #include<iostream>
    using namespace std;
    
    struct A{
        const int m;
        const int n;
        A()=default;
        //如果成员是const,那么要采用列表初始化
        A(int a,int b):m(a),n(b){}
        ~A(){}
    };
    
    int main()
    {
        const int a=10;
    //err:  a =200;
        // 如果类类型对象是只读的,其内部成员不是const,那么可以采用普通构造函数赋值
        const A b(10,20);
    //  b.m =20;
    //  b.n =200;
    
        return 0;
    }
    

    03_const_function.cpp

    #include<iostream>
    using namespace std;
    
    struct A{
        const int m;
        const int n;
        A()=default;
        //如果成员是const,那么要采用列表初始化
        A(int a,int b):m(a),n(b){}
        ~A(){}
        //如果访问只读成员,那么该方法也应该是const的
        int get_m()const{return m;}
        //任何方法只能以只读的方式访问const成员
        int set_m(int k)const{m=k;}
    };
    
    int main()
    {
        const int a=10;
    //err:  a =200;
        // 如果类类型对象是只读的,其内部成员不是const,那么可以采用普通构造函数赋值
        const A b(10,20);
        cout<<b.get_m()<<endl;
    //  b.m =20;
    //  b.n =200;
    
        return 0;
    }
    
  • 相关阅读:
    Windows网络编程经验小结
    异步Socket服务器与客户端
    用C#实现C/S模式下软件自动在线升级
    Linux 安装字体
    word 生成目录
    Linux sar使用
    yum 使用说明
    HASH JOIN算法
    row cache lock
    cursor: pin S
  • 原文地址:https://www.cnblogs.com/Sico2Sico/p/5384254.html
Copyright © 2011-2022 走看看