Effective C++ 条款3
来源:互联网 发布:mysql教程合集 编辑:程序博客网 时间:2024/04/30 00:08
尽可能使用const
const关键字在编程中的应用广泛,如何灵活的发挥它的优势值得我们探讨,
首先
理解什么是const,如何使用const。
我们看一下对于一个指针有关const的应用。
char g[]="hello";char *p=g;const char *p=g;//该指针指向的数据不可修改char *const p=g;//该指针自身的值不能修改const char * const p=g;//该指针指向数据不能修改,自身的值也不能修改
其次
有关迭代器的const性质
const_iterator迭代器不可以改变指向的数据,可以改变自己的值
例如:
std::vector<int>::const_iterator m;
接着
const 关键字可以实现重载
如下代码:
#include<iostream>using namespace std;class What{public: void Fun()const { cout << "const Fun"; } void Fun() { cout << "Fun"; } void Fun1() { cout << "Fun1"; }};int main(){ What const w; w.Fun();//调用const Fun cout << endl; const_cast<What&>(w).Fun();//调用Fun return 0;}
如上代码,const对象调用const函数,非const对象调用非const函数,而且大家都知道const对象不能调用非const函数。
最后
我们要明白对于一个类的const函数来书,const属性只对该类的成员数据有效,并且为了避免代码重复,我们选择非const同名成员函数嵌套const同名成员函数。
如下代码
class CTextBlock{public: const char& operator[](std::size_t position)const { //.......... return pText[position]; } char& operator[](std::size_t position) { return const_cast<char&>(static_cast<const CTextBlock&>(*this)[position]); } char * pText; int length;};
2 0
- Effective C++:条款01
- Effective C++:条款02
- Effective C++:条款03
- Effective C++:条款04
- Effective C++:条款05
- Effective C++:条款06
- Effective C++:条款07
- Effective C++:条款08
- 《effective C++》条款三
- 《effective C++》条款5
- 《effective C++》条款六
- Effective C++--经验条款
- Effective C ++ 条款34
- 《Effective C++》条款05
- 《Effective C++》条款06
- 《Effective C++》条款08
- 《Effective C++》资源管理:条款13-条款15
- 《Effective C++》资源管理:条款16-条款17
- css清除浮动
- JAVA中转义字符
- spring+mybatis 多数据源整合
- windows xp 恢复删除的分区
- Objective-C----NSSet 、 NSMutableSet 、 NSCountedSet
- Effective C++ 条款3
- Android数据库高手秘籍(一)——SQLite命令
- 天声人語 20150620
- Objective-C----快速枚举、数组排序
- 袖珍实干的卸载小软Soft Organizer,使用和测评:
- Android数据库高手秘籍(二)——创建表和LitePal的基本用法
- SQL 标量函数&表值函数
- static用法
- Apache web submit 403 error, access forbbiden, Undefined variable