让自己习惯C++

来源:互联网 发布:mac升级后windows没了 编辑:程序博客网 时间:2024/05/16 13:42

Item1 View C++ as a federation of languages。 C、Object-Oriected C++、Template C++、STL。

Item2 Prefer consts, enums, and inlines to #defines。比如#define ASPECT_RATIO 1.653替换为const double AspectRatio=1.653;

or 类的成员,例子如下:

class GamePlayer{private:static const int NumTurns=5;
        or enum {NumTurns=5}; //个人理解仅限于整数的情况
        int scores[NumTurns];};
具有表达式的复杂宏改用inline函数。 毕竟宏不进行语法检查,还要对实参加括号之类,容易引起麻烦。

Item3 Use const whenever possible.

const可以被用来修饰任何作用域的对象,函数参数,函数返回类型,成员函数体。

当const和non-const成员函数有实质等价的实现时,用non-const版本调用const版本可以避免代码重复。

例:

class CTextbox{public:const char& operator[](size_t position) const{return text[position];}char& operator[](size_t position){return const_cast<char&>(static_cast<const CTextbox&>(*this)[position]);}private:string text;};

Item4 Make sure that objects are initialized before they're used.

为内置型对象进行手工初始化,C++保证初始化他们。

构造函数使用成员初始化列表,而不是调用函数体内的赋值运算符来初始化。提高效率,直接调用构造函数而非先调用默认构造函数再调用赋值运算符。

为免除“跨边一单元的初始化次序”问题,以local static对象替代non-local static对象。

例如:

class FileSystem{ .... };FileSystem tfs;替换为FileSystem& tfs(){static FileSystem fs;return fs;}


在调用下面的函数的时候,一定回去调用fs对象的构造函数,保证了fs初始化。

原创粉丝点击