More Effective C++ - 章节二 : 操做符(operators)

5. 对定制的 "类型转换函数" 保持警觉函数

容许编译器执行隐式类型转换,害处多过好处,不要提供转换函数,除非你肯定须要。post

class foo
{
  foo(int a = 0, int b = 1);
  operator double() const;
  ...
};

foo test(1, 2);
double d = 0.5 * test; // 编译器会调用double进行隐式转换

上述类型隐式转换可能致使错误(非预期)的函数被调用。解决方法 1.相似于C++ string 同样,添加一个函数专门作转换,相似string的c_str()转换string为const char* .spa

``` class foo { foo(int a = 0, int b = 1); double asDouble() const; // 添加一个成员函数作转换 ... }; ```

2.使用 explicit 关键字 .代理

3.使用代理对象,也就是类中再加一个代理类作.code

6. 区别 increment/decrement 操做符的前置(prefix)和后置(postfix)形式对象

看一下前置和后置重载例子:内存

class foo{
public:
  foo& operator++();
  const foo operator++(int);

  foo& operator--();
  const foo operator--(int);
};

为了防止 "i++++" 状况出现,后置式返回了一个const对象。 所以,正常状况下咱们应该使用前置式,直接返回引用,而不是临时拷贝对象,效率会更高。ci

7. 千万不要重载&&,||和, 操做符rem

8. 了解各类不一样意义的new和delete编译器

new的主要介绍以下:

// 1.首先分配内存  2.执行构造函数
string *ps = new string("Memory Management");

// 分配内存
void* operator new(size_t size);

// 在 buffer 内存处构建foo对象
new (buffer) foo(int i);

2018年10月1日15:59:02

相关文章
相关标签/搜索