《Effective c++》学习笔记--Accustoming Yourself to C++
2016-10-09 10:24
260 查看
Item 01 : View C++ as a federation of languages
C++语言联盟分成4部分 :C
Object-Oriented C++
封装,继承,多态,虚函数。。。
Template C++ 这是C++泛型编程的部分
STL C++标准模板库
什么时候使用传值:
对于内置类型(C-like)来说,传值比传引用高效,但是对于用户自定义的类型来说,传引用往往更好。
Item 02 : Prefer consts,enums,and inlines to # define.
用宏定义常量可能会使人疑惑,如定义:#define ASPECT_RATIO 1.653
可能ASPECT_RATIO从未被编译器看见,也许在预处理器处理是已经被替换了。
因此可以用
const double AspectRatio=1.653来代替,使用常量可能比使用宏导致较小的代码量。
Item 03 : Use const whenever possible
const 关键字的作用总结:1. const “保护”变量不被修改。
const int x=5; //x为常量不能被修改 const greeting[]=”hello”;
char*p=greeting; //non-const pointer,non-const data const
char* p=greeting; //non-const pointer,const data char*
const=greeting; //const pointer,non-const data const char*
const p=greeting; //const pointer,const data;
2. const 修饰函数形参
当输入参数为用户自定义类型和抽象数据类型,应将值传递改为
const &传递,提高效率
3. const 修饰类的成员函数
int get() const; //不会修改数据成员
const成员函数承诺不改变其对象的逻辑状态,non-const成员函数没有这般的承诺,如果在const函索内调用non-const成员函数,就会有风险。
因此,在const成员函数内不要调用non-const成员函数。
4. 函数的返回值为const
可以避免那些没有道理的,与固定类型不兼容的行为。
Item 04 : Make sure that objects are intialized before they are used
1. 对于内置的对象进行手工初始化,c++不保证初始化他们
例如:下面描述正确的是int *p1 = new int[10];
int *p2 = new int10;
A. p1和p2申请的空间里面的值都是随机值
B. p1和p2申请的空间里的值都已经初始化
C. p1申请的空间里的值是随机值,p2申请的空间里的值已经初始化
D. p1申请的空间里的值已经初始化,p2申请的空间里的值是随机值
此题选C,对于内置类型,c++并不保证初始化,因此1中只是分配内存,而未初始化,而2中对其初始化为0。
2.构造函数最好用成员列表初始化,而不要在构造函数体内赋值操作
特别注意的一点就是,成员列表初始化的顺序应该和他在类中定义的顺序一致。相关文章推荐
- Effective C++ - Accustoming Yourself to C++
- 对象函数Effective C++ 读书笔记之Part1.Accustoming Yourself to C++
- Effective C++笔记 【1. Accustoming yourself to C++】
- Conclusion for Accustoming Yourself to C++
- Things to Remember: Accustoming Yourself to C++
- 经典图书评注:Accustoming Yourself to C++
- C++ Chapter 1. Accustoming Yourself to C++
- (Effective C++)第一章 让自己习惯C++(View Yourself to C++)
- 《Effective C++》学习笔记条款01 视C++为一个语言联邦
- 《Effective C++》学习笔记条款20 宁以pass-by-reference-to-const替代psss-by-value
- 《Effective C++》学习笔记条款10 令operator= 返回一个reference to *this
- 《Effective C++》学习笔记条款05了解C++默默编写并调用哪些函数
- C++ Coding Standards ---- Item0 : Don's sweat the small stuff.(Or : Know what not to standardize)
- Introduction to Using the XML DOM from Visual C++
- [总结]How to Shoot Yourself In the Foot
- Introduction to Programming in C/C++ with Vim
- How to learn c++
- How to interpret complex C/C++ declarations
- Data type conversion sheet : C++ to .NET
- How to Compile XviD with Microsoft Visual C++ 6.0(zhuan)