用AI赚第一桶💰低成本搭建一套AI赚钱工具,源码可二开。 广告
## 第6章 函数 ### 6.2.3 当形参有顶层const时,传给它常量对象或者非常量对象都是可以的。因此,当引用作为形参时,应尽量使用常量引用。 ### 6.2.6 **initializer_list**对象中的元素永远是常值。 ### 6.3.2 调用一个返回引用的函数得到左值,其他返回类型得到右值。 - 练习6.33 ```cpp /* 文件名:ex6.33.cpp */ /* C++ Primer中文版第5版, 练习6.33 */ /* 题目要求:编写递归函数,输出vector对象的内容 */ #include <iostream> #include <vector> using namespace std; using Iter = vector<int>::const_iterator; int print_recursion(Iter beg, Iter end) { if (beg == end) { cout << "End" << endl; return 0; } cout << *beg << " "; print_recursion(++beg, end); } int main(void) { vector <int> iv{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; Iter beg = iv.cbegin(), end = iv.cend(); print_recursion(beg, end); return 0; } ``` ### 6.3.3 尾置返回类型(trailing return type)跟在形参列表后面并以->符号开头,而在函数名前用auto关键字修饰。 ```cpp auto func(int i) -> int(*)[10];//返回一个指向含有10个整型的数组的指针 ``` ### 6.4 函数重载 - 不允许两个函数除了返回类型外其他所有的要素都相同。即返回类型差异不被视为重载依据。 - 当我们传递一个非常量对象或者指向非常量对象的指针时,编译器会优先选用非常量版本的函数。 ### 6.5.1 在给定的作用域中一个形参只能被赋予一次默认实参。换句话说,函数的后续声明只能为之前那些没有默认值的形参添加默认实参,而且该实参右侧的所有形参必须都有默认值。 ### 6.5.2 内联函数和constexpr函数 - **constexpr函数**的返回类型及所有形参的类型都得是字面值类型,而且函数体中必须有且只有一条实际操作语句(return语句)。 - **constexpr函数**被隐式地指定为内联函数。 - 内联函数和constexpr函数可以在程序中多次定义,因此通常定义在头文件中。 ### 6.7 函数指针 编译器不会将函数返回类型当成对应的指针类型处理。 - 6.7节练习 ```cpp /* 文件名:ex6.54.cpp */ /* C++ Primer中文版第5版, 6.7节练习 */ /* 题目要求: 函数指针的应用 */ #include <iostream> #include <vector> using namespace std; int myAdd(int a, int b) { return a + b; } int mySub(int a, int b) { return a - b; } int myMul(int a, int b) { return a * b; } int myDiv(int a, int b) { //return a / b; return b != 0 ? a / b : 0;//处理除数为0的情况 } int main(void) { int Fun(int, int); int a, b; vector <decltype(Fun)*> vpFun; vpFun.push_back(myAdd); vpFun.push_back(mySub); vpFun.push_back(myMul); vpFun.push_back(myDiv); cout << "Enter 2 integers, separated by space: "; cin >> a >> b; cout << "add: " << vpFun[0](a, b) << endl; cout << "sub: " << vpFun[1](a, b) << endl; cout << "mul: " << vpFun[2](a, b) << endl; cout << "div: " << vpFun[3](a, b) << endl; //system("pause");//调试环境:VS2013, Debug Win32 return 0; } ``` 运行效果: ![6.7节练习运行截图](https://box.kancloud.cn/4ee375313049c51c694bf344a5179f1c_339x110.png =339x110)