这本书有九个章节,每一个章节都对特定C++使用方面进行了讲述,并提供了一些建议(条款),本篇笔记也将以书本顺序编写并配以目录,以方便读者快速查阅。

让自己习惯C++

explicit

禁止类对象之间的隐式转换,以及禁止隐式调用拷贝构造函数。

eg:

先看看不使用explicit的时候,以下代码会把10调用对象之间的隐式转换,这样exp1的值就变成了{10, 1}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

class B {
public:
B(int x = 0, bool b = true);
};

B::B(int x, bool b) {
cout << x << ": " << sizeof(x) << endl;
cout << b << ": " << sizeof(b) << endl;
}

int main() {
B exp1 = 10;
return 0;
}

如果加上了explicit关键字,编译时就会报错
“pre.cpp: In function ‘int main()’:
pre.cpp:15:14: error: conversion from ‘int’ to non-scalar type ‘B’ requested
B exp1 = 10;”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

class B {
public:
explicit B(int x = 0, bool b = true);
};

B::B(int x, bool b) {
cout << x << ": " << sizeof(x) << endl;
cout << b << ": " << sizeof(b) << endl;
}

int main() {
B exp1 = 10;
return 0;
}

Prefer consts,enums,and inlines to #define

在程序编译阶段前的预处理阶段,由define定义的符号会被做文本替换,也就是说实际上当程序运行时,那个被替换的符号已经没有被记录了(符号表不记录)。这样当你的程序出现错误时,编译器报出的错误你将难以判别了。

1
#define A 1.22

改成

1
const double A 1.22

const

当你想给一个类中的某个变量予以不变的常量,并且这个类的实例都可以访问它

1
2
3
4
5
class A {
private:
static const int a = 5;
int arrs[a];
}