【Effective C++】让自己习惯C++

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

C++的四个组成部分:C、C With Classes、Template C++、STL

 

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

  • 常量用const和enums替换#define
  • 用inline函数替换带参宏(#define)

 

条款03:尽可能使用const

  • const修饰函数返回值:降低操作错误导致的意外
  • const修饰成员函数:表明该函数不能改变对象内容、操作const对象(const修饰成员函数可作为重载条件、const成员函数不能调用非const成员函数)
 1 class Text{
 2 private:
 3     std::string text;
 4 public:
 5     ...
 6     const char& operator[](std::size_t pos) const
 7     {return text[pos];} //const版本,在const对象上使用时重载此函数
 8 
 9     char& operator[](std::size_t pos); 
10     {return text[pos];} //非const版本
11 
12     char& operator[](std::size_t pos) const;
13     {return text[pos];} //不正确的const版本,const修饰函数说明该函数并不能修改成员但返回值却留出了修改的余地
14 
15 };

 

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

  • 对每个内置类型对象进行初始化
  • 构造函数初始化列表的顺序和类中的声明顺序保持一致
  • C++对non-local static对象的初始化顺序没有定义,local static对象在首次调用期间初始化,因此为了避免初始化顺序造成的问题可以用local static对象替代non-local static对象。

 

posted @ 2022-03-28 16:47  axingzheng  阅读(37)  评论(0)    收藏  举报