1 view c++ as a federation of languages
c
pass by value比pass by reference更高效,c中的引用实质上还是指针
object-oriented c++
有构造函数和析构函数存在,传值会调用拷贝构造函数和析构函数
template c++
pass by reference 更高效,在使用模版时,并不知道是什么类型,使用reference不用拷贝
pass by reference-to-const
STL
2 prefer const enum inline to define
1 |
|
const 比define更好
1 | class foo{ |
num是类中的专属常量,如果在类外取它的地址的话,需要在类外给出定义式
1 | const int foo::num; |
1 |
|
如果不在类外给出定义式,在类外访问num的地址会出现错误,原因是并没有给num分配内存
1 | class foo { |
也没分配地址,所以要在外面给出定义式,在类中仅仅只是声明式
1 | class foo { |
像这样,虽然能够输出num的值,但是并没有给num分配内存,仅仅只是替换成5
也可以这样写
1 | class foo{ |
使用inline替换’#define’
3 use const whenever possible
4 初始化后再使用
1 | class ABEntry { |
对于下面的构造函数
1 | ABEtry::ABEntry(const std::string& name, const std::string* address, const std::list<std::string> phones) { |
参数是在进入构造函数前就初始化了,上面的操作是赋值,不是初始化
正确的做法是使用member initialization list
1 | ABEntry::ABEntry(const std::string& name, const std::string& address, const std::list<std::string> phones) |
赋值版本的构造函数,首先会调用default构造函数为参数设置初值,然后立刻赋予新值