const修饰类的成员函数
来源:互联网 发布:淘宝客qq群如何拉人 编辑:程序博客网 时间:2024/05/16 02:50
《Effective C++》里面说,尽量使用const,const修饰变量一般有两种方式:const T a,或者 T const *a,这两者都是一样的,主要看const位于的左边还是右边,这里不再赘述,主要来看一下当const修饰类的成员函数时,成员函数有什么特点。
类的成员函数后面加 const,表明这个函数不会对这个类对象的数据成员(准确地说是非静态数据成员)作任何改变。
在设计类的时候,一个原则就是对于不改变数据成员的成员函数都要在后面加 const,而对于改变数据成员的成员函数不能加 const。所以 const 关键字对成员函数的行为作了更加明确的限定:有 const 修饰的成员函数(指 const 放在函数参数表的后面,而不是在函数前面或者参数表内),只能读取数据成员,不能改变数据成员;没有 const 修饰的成员函数,对数据成员则是可读可写的。
除此之外,在类的成员函数后面加 const 还有什么好处呢?那就是常量(即 const)对象可以调用 const 成员函数,而不能调用非const修饰的函数。
注意:两个成员函数如果只是常量性不同,是可以被重载的
例如:
class A{public: void f() { cout<<"non const"<<endl; } void f() const { cout<<" const"<<endl; } };
微软笔试第二题正是考这个,const 对象调用f() const,非const对象调用 f()
from:
http://blog.sina.com.cn/s/blog_628571e60101e0vb.html
0 0
- const修饰的类成员函数
- const修饰类的成员函数
- const修饰类的成员函数
- const修饰类的成员函数
- const修饰类的成员函数
- const修饰类的成员函数
- const修饰的成员函数
- const 之 const修饰的成员函数
- const修饰成员函数
- const修饰成员函数
- const 修饰成员函数
- const修饰成员函数
- const 修饰的常函数成员
- const修饰成员函数const修饰对象
- const修饰成员函数总结
- C++ const 修饰成员函数
- C++ const 修饰成员函数
- C++类数据成员和成员函数const修饰
- 如何使用 TinyXML 在内存中操作 xml 格式的内容
- IOS开发笔记 之 socket链接 与 http链接的区别
- HDU 1159 Common Subsequence 公共子序列
- PHP开发安全问题总结
- Leetcode# 73 Set Matrix Zeroes
- const修饰类的成员函数
- 【随笔】未来的路
- JS判断是什么设备是什么浏览器-主要用移动页面开发
- 学习笔记-gitHub使用
- Android Activity 组件生命周期
- poj 2431 Expedition 优先队列 大顶堆
- 数字图像处理02(直方图及均衡化,规定化,局部对比度增强)
- iOS操作小整理
- [HDU 1043] Eight A*或IDA*