您的位置:首页 > 编程语言 > C语言/C++

c++ const 类

2016-03-30 10:54 127 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: