A tour of C++ Book Note Day2
Just for share my note when I reading the book. If you want to discuss what interests you, you can write in the comments section. If there is a dispute, you can corret it!
1.3 Function
Function/declaration quote8
- 一个函数的声明可能包含参数名,这对于编码者/阅读者是有帮助的,但是如果该函数只是一个声明/定义而非实现,那么对于编译器来说,它所看见的将不会有参数名
A function declaration may contain argument names. This can be a help to the reader of a program, but unless the declaration is also a function definition, the compiler simply ignores such names. ^quote8
// if we just delclarate a function:
double sqrt(double var);
// the compiler will ignore such names, just like:
double sqrt(double var); -> double sqrt(double);
// but if you declarate and implement a funtion:
double sqrt(double var) {} -> double sqrt(double var) {} // the compiler saw
Function/function_type quote9
- 不仅仅对于值来说有类型,函数一样也是有类型的,在编译器看来,函数的类型就是函数的返回值类型 + 参数列表的各参数的类型
The type of a function consists of its return type followed by the sequence of its argument types in parentheses. ^quote9
// for exmaple, there is a function
double get(std::vector<double>& vec, int index);
// -> the type: double(std::vector<double>, int)
Function/member_function_type quote10
- 对于类中的成员函数来说,其类型不仅仅只有返回值类型和列表类型,还需要带上类作用域来指定具体类型
For such a member function, the name of its class is also part of the function type ^quote10
// if we code a String class with a operator[]
char& String::operator[] (int index);
// -> the type: char& String::(int)
Function/trans2 quote11
- 代码的可维护性第一步在于代码的可读性。实现可读性的第一步就是将计算任务分成各种有意义的小堆(将其以函数或者类的形式表示)并将其命名
We want our code to be comprehensible because that is the first step on the way to maintainability.
The first step to comprehensibility is to break computational tasks into meaningful chunks (represented as functions and classes) and name those. ^quote11
Function/trans3 quote12
- 代码中的错误量与代码量和代码复杂程度有着强相关
- 代码数量越多,就意味着代码后期维护工作量的增长,而复杂程度就不可避免的压低了代码的可读性
The number of errors in code correlates strongly with the amount of code and the complexity of the code. ^quote12
Function/trans4 quote13
- 使用函数来做一些特殊化的任务(准确来说应该是特定的模块)通常能够让我们避免在其他代码中杂糅
- 最简单的例子就是,模块化,每一个函数对应一个单一的功能
Using a function to do a specific task often saves us from writing a specific piece of code in the middle of other code; ^quote13
Function/trans5 quote14
- 如果我们无法对一个函数进行合适的命名,这很有可能意味着我们对该函数模块的设计有问题
- 显然的,如果无法对一个函数的具体作用摸棱两可,那么该函数在后续的作用也会是杂乱无章的
If we cannot find a suitable name, there is a high probability that we have a design problem. ^quote14
Function/trans6 quote15
- 当一个函数被重载时,对于每一个基于该函数的重载函数都应该实现相同的语义
- 也就是说,建议重载函数都是对相同功能的一个扩展,尽量不要使用重载函数去完成与原函数相悖的功能
When a function is overloaded, each function of the same name should implement the same semantics. ^quote15
// source function
void print(int) {}
// in this case, the 'print' function just want to print the value of type
void print(double) { //... }
// but if you code a 'print' function but use it to output the sum of all var of double type -> when someone use it, it will find that the function is ambiguous.