第2章
#include <iostream> //预处理器
using namespace std
2.1函数介绍
启动函数调用的函数是调用方,被调用的函数是被调用方或被调用函数
2.2 用户定义函数
returnType functionName() // 函数头
{
// 函数体
}
2.3函数返回值(值返回函数)
使用return语句返回值。
如果未提供return语句,函数main将隐式返回0。
每次调用时只能返回单个值。
2.4 void函数(无值返回函数)
不需要返回语句
#include <iostream>
// void means the function does not return a value to the caller
void printHi()
{
std::cout << "Hi" << '\n';
// This function does not return a value so no return statement is needed
}
int main()
{
printHi(); // okay: function printHi() is called, no value is returned
return 0;
}
2.5 函数参数和参数简介
函数参数是函数头中使用的变量,使用函数调用方提供的值进行初始化。
参数是进行函数调用时从调用方传递给函数的值:
// This function takes no parameters
// It does not rely on the caller for anything
void doPrint()
{
std::cout << "In doPrint()\n";
}
// This function takes one integer parameter named x
// The caller will supply the value of x
void printValue(int x)// int x 函数参数:局部变量
{
std::cout << x << '\n';
}
// This function has two integer parameters, one named x, and one named y
// The caller will supply the value of both x and y
int add(int x, int y) //int x, int y 函数参数:局部变量
{
return x + y;
}
int main()
{//函数调用方
std::cout << add(4, 5) << '\n'; // Arguments 4 and 5 are passed to function add()
return 0;
}
2.6 局部变量
局部变量:函数参数及函数体内定义的变量
局部变量生存期:局部变量在定义它的花括号集末尾(或者对于函数参数,在函数末尾)以与创建顺序相反的顺序销毁。
#include <iostream>
void doSomething()
{
std::cout << "Hello!\n";
}
int main()
{
int x{ 0 }; // x's lifetime begins here
doSomething(); // x is still alive during this function call
return 0;
} // x's lifetime ends here
当调用函数时,如果将被调用函数至于主函数之后,会出错,可以使用前向声明
前向声明:在主函数main之前告诉编译器函数的存在
使用函数声明语句(函数原型)。函数声明由函数的返回类型、名称和参数类型组成,以分号结尾。
#include <iostream>
int add(int x, int y); // 前向声明
int main()
{
std::cout << "The sum of 3 and 4 is: " << add(3, 4) << '\n'; // this works because we forward declared add() above
return 0;
}
int add(int x, int y) // even though the body of add() isn't defined until here
{
return x + y;
}
函数声明不需要指定参数的名称。
//上面的前向声明语句可以修改为如下:
int add(int, int); // valid function declaration
宏定义:采用#define指令
两种类型的宏:类对象宏和类函数宏。
类对象宏的定义:
#define identifier #define identifier substitution_text
具有substitution_text的类对象宏
当预处理器遇到此指令时,标识符的任何进一步出现都将替换为 substitution_text
#include <iostream>
#define MY_NAME "Alex"
int main()
{
std::cout << "My name is: " << MY_NAME << '\n';
return 0;
}
// The contents of iostream are inserted here
int main()
{
std::cout << "My name is: " << "Alex" << '\n';
return 0;
}
运行时,打印输出.My name is: Alex
2.7 条件编译
:#ifdef、#ifndef、#endif
2.8 头文件(.h)
add.h:
int add(int x, int y); // function prototype for add.h
main.cpp
#include "add.h" // Insert contents of add.h at this point.
#include <iostream>
int main()
{
std::cout << "The sum of 3 and 4 is " << add(3, 4) << '\n';
return 0;
}
add.cpp
#include "add.h" // Insert contents of add.h at this point.
int add(int x, int y)
{
return x + y;
}
第3章
代码调试
1.验证代码流:在打印信息以进行调试时,使用std::cerr而不是std::cout
2.打日志:使用plog记录器
3.使用集成调试器:单步执行、设置断点、监视变量、调用堆栈