0
点赞
收藏
分享

微信扫一扫

《Effective C++ 改善程序与设计的55个具体做法》 第一章 笔记


1 让自己习惯C++

 

条款01:视C++为一个语言联邦

        View C++ as a federation of languages.

 

“C++的语法多样复杂,简单来看,可以把它看成4种语言(C、面向对象、Tempate(模板)、STL(标准库)。”

 

 

C。 C是C++的基础,C++的区块、语句、预处理器、内置内置数据类型、数组、指针都来自于C。

Object-Oriented C++。这部分是C with classes所诉求的:classes、封装、继承、多态、virtual……

Template C++。 C++的泛型编程(generic programming)部分

STL。 STL是个template库。

 

 

条款02:尽量以const,enum,inline替换#define

         Prefer consts,enums,and inlines to #defines

 

“对于单纯常量,最好用const或enum ;

对于形似函数的宏,建议用inline函数”

 

例如:#define ASPECT_RATIO 1.653 改为 const double AspectRatio = 1.653;

       class专属常量。

              class GamePlayer {

                     private:

                            static const int NumTurns = 6;

                            int scores[NumTurns];

                           …};

如果编译器不允许这种做法,可改用the enum hack做法:

              class GamePlayer {

                     private:

                            enum{NumTurns = 5};

                            int scores[NumTurns];

                           …};

 

             

 

条款03:尽可能使用const

         Use const whenever possible

 

“如果一个东西应该是const的,就尽量用const限制。”

 

1、关键字const出现在星号*左边,表示被指物是常量,星号*出现在右边,表示指针自身是常量。

2、令函数返回一个常量值,可以避免一些错误操作。

例如:

class Rational {…};

const Rational operator* (const Rational & lhs,const Rational& rhs);

这样当出现

Rational a,b,c;

(a*b)= c;    这种错误操作就会报错。

3、const成员函数

 

条款04:确定对象被使用前已先被初始化

         Make sure that objects are initialized before they’re used

 

“永远在使用对象前将其初始化,对于无任何成员的内置类型,你必须手工初始化。”

 

int x = 0;

const char * text = “A C-style string”;

double d; std::cin>>d;

对于内置类型以外的东西,初始化需要在构造函数(constructors)的成员初始化列表中进行。

ABEntry::ABEntry(const std::string &name, const std::string&address)

:theName(name),theAddress(address) {}

举报

相关推荐

0 条评论