C++primer5阅读笔记2(C++编程小贴士2)
1、不要返回局部变量的引用和指针
2、arr表示的类型是含有10个整数的数组
typedef int arr[10];
using arr = int[10];
3、
auto func(int i) -> int* [10];
4、函数返回中使用decltype,P232
5、
int a[2] = "ab"; # 错误,没有空间存放空格
6、不能把一个数组赋值给另一个数组
7、指针加上一个整数后,最多可以指向数组尾部的下一个元素
8、C风格字符串:
strlen(p); #p需以空格结果,但不计数
strcmp(p1,p2);
strcat(p1,p2);
strcpy(p1,p2);
9、与旧代码的接口 P137
10、const_cast和重载 P235
11、重复声明:
string fcn(int, int, char = ' ');
string fcn(int, int, char = '*');
12、内联函数可以避免函数调用的开销
13、内联函数和constexpr函数 P239
14、调试帮助:assert预处理宏、NDEBUG预处理变量(P242)
15、
struct Sales_data
{
Sales_data() = default;
#默认构造函数,等同于合成默认构造函数
Sales_data(const std::string &s):bookNo(s) {}
Sales_data(const std::string &s, unsigned n, double p):bookNo(s), units_sold(n), revenue(p*n) {}
Sales_data(std::istream &);
}
Sales_data::Sales_data(std::istream &is)
{
read(is, *this);
#从is中读入一条交易信息,然后存入this中
}
int main()
{
std::istream &is = std::cin;
Sales_data a(is);
#初始化
}
16、class、struct的区别在于默认的访问权限,class是private,struct是public
17、inline成员函数与相应的类定义在同一个头文件中
18、管理动态内存的类则不能依赖于拷贝和赋值操作的默认版本,而且也应该尽量使用string和vector来避免动态管理内存的复杂性
19、类和非成员函数的声明不是必须要在他们的友元声明之前的
20、编译器处理完类中的全部声明后才会处理成员函数的定义
21、const或者引用,必须初始化
22、默认构造函数:不传递任何参数就可以被调用的构造函数
23、explicit构造函数只能用于直接初始化
24、类的静态成员 P295
25、非静态数据成员不能作为成员函数默认实参
26、rate应该是一个常量表达式;而类内只能初始化整型类型的静态常量,所以不能在类内初始化vec:
// example.h
class Example {
public:
static constexpr double rate = 6.5;
static const int vecSize = 20;
static vector<double> vec;
};
// example.C
#include "example.h"
constexpr double Example::rate;
vector<double> Example::vec(Example::vecSize);