| 日期 | 变更记录 |
|---|---|
| 2021-10-20 | 创建 |
按值传递总结完后才发现,这是打底裤~
按引用传递函数调用中复制参数的值
函数只能访问自己创建的副本
对副本进行的更改不会影响原始变量
函数的默认参数函数调用中传递参数的引用
引用就是别名
&符号告诉编译器将变量作为引用
大的数据结构按引用传递,效率非常高
将引用声明为常量,不能再绑定别的对象
内联函数一旦给一个参数赋值,则后续所有参数都必须有默认值
优点:如果使用的参数在函数中几乎总是采用相同的值,则默认参数非常方便
传递给函数的形参有默认参数的话,函数会输出传递的形参的值
函数重载内联函数节省短函数的执行时间
Example 按值传递编译器通过调用时参数的个数和类型确定调用哪个函数
函数名相同,函数参数类型不同构成重载
函数名相同,函数个数不同构成重载
优点:不必使用不同的函数名、有助于理解和调试代码、易于维护代码
#if 1 #include按指针传递using namespace std; //按值传递:传值就是传副本 void swap(int a, int b) { int temp; temp = a; a = b; b = temp; cout << "a" << a << endl; cout << "b" << b << endl; } int main() { int x = 20, y = 30; swap(x, y); return 0; } #endif
#if 1 #include按引用传递using namespace std; void swap1(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; cout << "a" << *a << endl; cout << "b" << *b << endl; } int main() { int x = 20, y = 30; swap1(&x, &y); return 0; } #endif
#if 1 #include默认参数 函数自带默认参数using namespace std; void swap2(int &a, int &b) { int temp; temp = a; a = b; b = temp; cout << "a" << a << endl; cout << "b" << b << endl; } int main() { int x = 20, y = 30; swap2(x, y); return 0; } #endif
#if 1 #include函数带默认参数,传递形参的值using namespace std; void fun(int a=10, int b=20, int c=30) { cout << a << endl; cout << b << endl; cout << c << endl; } int main() { fun(); return 0; }
#if 1 #include内联函数using namespace std; void fun1(int a, int b = 20, int c = 30); int main() { fun1(10, 2); return 0; } void fun1(int a, int b, int c) { cout << a << endl; cout << b << endl; cout << c << endl; } #endif
#if 1 #include函数重载 函数参数类型不同构成重载using namespace std; //内联函数是直接展开的, 不要经过调用 //内联函数,一般是比较短小,且在短时间内频繁调用 inline void fun() { cout << "hello" << endl; } int main() { fun(); return 0; } #endif
#if 1 #include函数参数个数不同造成重载using namespace std; void add(float a, float b) { cout << "float:" << a + b << endl; } void add(int a, float b) { cout << "int_float:" << a + b << endl; } void add(float a, int b) { cout << "int_float:" << a + b << endl; } int main() { add((float)10.1, 20); add(10.1f, 10.2f); add(10, 10.1f); return 0; } #endif
自行幻想~



