cs10b笔记
Overview of C++
The structure of a C++ program
comments
语法:/*...*/
or //
,前者是多行注释,后者是单行注释
Library inclusions
#include
This line instructs the C++ compiler to read the relevant definitions from what is called a header file.
Those header files typically end with the suffix .h and are enclosed in quotation marks instead of angle brackets.
可是在开发大项目的时候,头文件很多,可能会出现头文件名字重复的问题,那么为了解决这个问题,c++提出了namespaces
这个东西。
To ensure that the names defined in different parts of a large system do not interfere with one another, the designers of C++ made it possible to segment code into structures called namespaces, each of which keeps track of its own set of names.
The standard C++ libraries use a namespace called std
Increasingly, professional C++ programmers specify the namespace explicitly by adding the prefix std:: before each name to which it applies. Using this approach, the first line of the HelloWorld program becomes
1 | std::cout << "hello, world" << std::endl; |
Function prototypes
函数原型
Although the definitions of these functions appear toward the end of the file, the PowersOfTwo program provides a concise description of the raiseToPower function just after the library inclusions. This concise form is called a prototype and makes it possible to make calls to that function before its actual definition appears.
The main program
Every C++ program must contain a function with the name main. This function specifies the starting point for the computation and is called when the program starts up. When main has finished its work and returns, execution of the program ends.
Name conventions
Defining functions in C++
Overloading
Using the same name for more than one version of a function is called overloading. The pattern of arguments taken by a function—which refers only to the number and types of the arguments and not the parameter names—is called its signature.
The compiler chooses which of these versions to invoke by looking at the types of the arguments the caller provides.
The primary advantage of using overloading is that doing so makes it easier for you as a programmer to keep track of different function names for the same operation when it is applied in slightly different contexts.
If, for example, you need to call the absolute value function in C, which does not support overloading, you have to remember to call fabs for floating-point numbers and abs for integers. In C++, all you need to remember is the single function name abs.
The steps in calling a function
跟cs61A上的函数调用过程是一致的,但是这个没图,python那个有图介绍,更清楚些。
Reference parameters
如果需要在函数中修改传递进去的参数,需要将参数变为reference parameters
,在定义函数的时候,需要在参数名字前加上&
符号。
比如:
void setToZero(int & x);
用途:
In C++, one of the most common uses of call by reference occurs when a function needs to return more than one value to the calling program.
就是把函数作为一个过程,修改传递进去的参数的值,从而达到返回多个结果的效果