大的网站建设公司,正邦设计公司简介,镇江市质监站网址,手机可填写简历模板免费目录 一、函数的默认参数
二、函数占位参数
三、函数重载
四、函数重载-注意事项 一、函数的默认参数
在C中#xff0c;函数的形参列表中的形参是可以有默认值的
语法#xff1a;返回值类型 函数名 #xff08;参数默认值#xff09;{} 示例1#xff1a;
#includ…目录 一、函数的默认参数
二、函数占位参数
三、函数重载
四、函数重载-注意事项 一、函数的默认参数
在C中函数的形参列表中的形参是可以有默认值的
语法返回值类型 函数名 参数默认值{} 示例1
#includeiostreamusing namespace std;// 函数的默认参数int func(int a,int b,int c){return abc;}int main(){func(10,20);return 0;}
错误显示
传入参数少。 示例2
#includeiostreamusing namespace std;// 函数的默认参数int func(int a,int b20,int c30){return abc;}int main(){coutfunc(10)endl;;return 0;}
运行结果 示例3
#includeiostreamusing namespace std;// 函数的默认参数// 如果我们自己传入数据就用自己的数据如果没有那么就用默认值int func(int a,int b20,int c30){return abc;}int main(){coutfunc(10,40)endl;;return 0;}
运行结果 注意事项
// 1. 如果某个位置参数有默认值那么这个位置往后从左往右必须有默认值
// 2. 如果函数声明有默认值函数实现的时候就不可以有默认参数声明和实现只有一个有默认参数 示例
#includeiostreamusing namespace std;// 函数的默认参数// 如果我们自己传入数据就用自己的数据如果没有那么就用默认值int func(int a,int b20,int c30){return abc;}int func2(int a10,int b10);int func2(int a,int b){return ab;}int main(){coutfunc(10,40)endl;coutfunc2func2()endl;return 0;}
运行结果 二、函数占位参数
C中函数的形参列表可以有占位参数用来做占位调用该函数时必须填补该位置
语法返回值类型 函数名 数据类型{}
void func (int a, int) // 第二个参数就是占位用的
func(10,10);// 必须传入参数才可以调用该函数
示例
#includeiostreamusing namespace std;// 占位参数void func(int a,int){coutthis is a funcendl;}// 占位参数也可以有默认值void func2(int a,int 20){coutthis is a func2endl;}int main(){func(10,40);// 占位参数必须填补func2(10);return 0;}
运行结果 三、函数重载
作用函数名可以相同提高复用性
函数重载要满足的条件
同一个作用域下函数名称相同函数参数类型不同或者 个数不同或者顺序不同
注意函数的返回值不可以做为函数重载的条件有默认参数的情况也不可以
示例
#includeiostreamusing namespace std;// 函数重载void func(){coutfunc函数的调用!endl;}void func(int a,int b10){cout有参数的func函数调用endl;}void func(double a){cout有参数且参数类型与上一个不同的func函数调用endl;}void func(int a,double b){coutfunc(int a,double b)的调用endl;}void func(double a,int b){coutfunc(double a,int b)的调用endl;}// 注意事项// 函数的返回值不可以作为函数重载的条件/*int func(double a,int b){coutfunc(double a,int b)的调用endl;}*/int main (){func();func(10);func(3.14);func(10,3.14);func(3.14,10);return 0;}
运行结果 四、函数重载-注意事项
引用作为重载条件函数重载碰到函数默认参数
#includeiostreamusing namespace std;// 函数重载的注意事项//1、引用作为重载的条件void func(int a){coutfunc(int a)函数的调用!endl;}// 两个函数的区别是参数类型不同void func(const int a){coutfunc(const int a)函数调用endl;}// 函数重载碰到默认参数的情况void func2(int a){coutfunc2(int a)的调用endl;}void func2(int a,int b10){coutfunc2(int a,int b10)的调用endl;}int main (){int a10;const int b10;func(a); // 传入一个变量的时候默认是没有const执行func(b);func(10);// 传入一个常量或者const修饰的变量执行的是有const修饰的函数coutendl;//func2(10);// 有默认值的时候两个函数都可以使用有歧义避免这样设置func2(10);// b没有默认值的时候可以使用func2(10,20);// 这样就很明确即使有默认参数也不影响函数的调用return 0;}
运行结果