c++中const修饰类及其成员小结
来源:互联网 发布:网络上不受欢迎的行为 编辑:程序博客网 时间:2024/06/01 01:34
1、const修饰类的成员变量。
const修饰类的成员变量,表示成员常量,不能被修改,同时它只能在初始化参数列表中赋值(C11支持类中初始化)。可被const和非const成员函数调用,而不可以修改。
class A{public: A():iValue(521){}private: const int iValue;}
2、const修饰类的成员函数。
1、const修饰函数的意义:承诺在本函数内部不会修改类内的数据成员,不会调用其他的非const成员函数。其从函数层面上不修改数据。2、const修饰函数的位置:const关键字放在声明之后,实现体之前。
class A {public: A():x(521),y(125){} void dis() const //const对象调用时,优先调用 { cout<<"x="<<x<<endl; cout<<"y="<<y<<endl; //y = 521; const修饰函数表示承诺不对数据成员修改 //input(); const修饰函数不能调用非const函数 } void dis() //构成函数重载,非const到对象时,优先调用 { y = 521; input(); cout<<"x="<<x<<endl; cout<<"y="<<y<<endl; } void input() { cin>>y; }private: const int x; int y;}
3、const修饰类的对象。
const修饰类对象表示常对象,其在对象层面上承诺不修改数据。
const A a;a.dis();
总结:
1、如果const构成了函数重载,const对象只能调用const函数,非const对象优先调用非const函数。
2、const函数只能调用const函数。非const函数可以调用const函数。
3、类体外定义的const成员函数,在定义和声明处都需要const修饰符。
4、const对象只能调用const函数,但可以访问非const和const数据成员,但不能修改。
1 0
- c++中const修饰类及其成员小结
- const修饰成员函数及其相关
- C++类中const成员小结
- C中Const小结
- const修饰类成员和类对象
- static和const修饰的类成员
- static和const修饰的类成员
- const修饰的类成员函数
- 用const修饰的类成员
- static和const修饰的类成员
- 类成员的const, static修饰
- const修饰类的成员函数
- const修饰类的成员函数
- const修饰类的成员函数
- const修饰类的成员函数
- const修饰类的成员函数
- const修饰成员函数
- const修饰成员函数
- 银行结算户和储蓄户区别
- 注册建筑师取消【官方已公布】
- Centos 6.4 python 2.6 升级到 2.7
- js常用正则
- java 得到10个1至20之间的随机数,要求不能重复,并将这10个数装入到数组中
- c++中const修饰类及其成员小结
- 使用BottomNavigationBar遇到的问题
- Android 6.0 Reboot 流程源代码分析
- java实现一个叫简单的xml解析
- Android系统架构的详细解析——很全面
- ci 3.0 默认路由放在子文件夹 无法访问的解决办法
- Linux 学习笔记(二) -----文件处理命令
- 小银考呀考不过四级
- java 8 不能兼容 instant run 解决方法记录 lambda expression are not supported at this laungh level