函数的默认参数
函数的参数可以有默认值
示例:
#include<iostream>
using namespace std;
int func(int a,int b=20,int c=30){
return a+b+c;
}
int main(){
// cout<<func(10);
cout<<func(10,30);//运行成功,说明传参先用传过参,没有才用默认参数
return 0;
}
- 注意:
- 如果某个位置已经有了默认参数,那从这个参数从左往右都要有(eg: a有值,则b,c都要有)
- 如果函数声明有默认参数,函数实现就不能有默认参数
示例:
int fun(int a = 10,int b =20)
int fun(int a = 10,int b =20){
return a+b;
}//输出err
函数的占位参数
- 含义:比如 func(int)就有数据类型即可
- 注意:main中也要有对应的参数
- 其他:占位参数也可以有默认参数
示例:
#include<iostream>
using namespace std;
void func(int a,int){
cout<<"this is func"<<endl;
}
int main(){
func(10,10);
// func(10); //err
return 0;
}
函数的重载
- 含义:可以让函数名相同,提高复用性
- 函数重载的满足条件:
- 同一个作用域下
- 函数名相同
- 函数参数类型不同,或者个数不同,或者顺序不同
示例:
#include<iostream>
using namespace std;
void func(){
cout<<"func的调用"<<endl;
}
void func(int a){
cout<<"func(int a)的调用"<<endl;
}
void func(int a,double b){
cout<<"func(int a,double b)的调用"<<endl;
}
void func(double a,double b){
cout<<"func(double a,double b)的调用"<<endl;
}
////函数返回值不可以占位函数的重载条件
//int func(double a,double b){
// cout<<"func(double a,double b)的调用"<<endl;
//}
int main(){
func(1,2);
func(1.2,2);
return 0;
}
- 注意:
- 引用作为重载条件
- 函数重载碰到函数默认参数
示例:
#include<iostream>
using namespace std;
//1.引用占位重载的条件
//void func(int &a){
// cout<<"func(int &a)调用"<<endl;
//}
//void func(const int &a){
// cout<<"func(const int &a)调用"<<endl;
//}
//2.函数重载碰到默认参数
void func2(int a,int b =10){
cout<<"func2(int a,int b = 10)调用"<<endl;
}
void func2(int a){
cout<<"func2(int a)调用"<<endl;
}
int main(){
// int a = 10;
// func(a);
// func(10);
func2(10);//当函数重载碰到没人参数,出现二义性
return 0;
}
本文详细介绍了C++中函数参数的使用方法,包括默认参数、占位参数和函数重载等概念。通过具体示例解释了如何设定及使用这些参数,并讨论了函数重载时的注意事项。

被折叠的 条评论
为什么被折叠?



