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;
}
原文地址:https://www.cnblogs.com/Sico2Sico/p/5384254.html