C++面向对象编程——函数
·
int func(int a,int b = 10,int c = 10){
return a+b+c;
}
//如果某个位置已经有了默认参数,那么从这个位置往后,从左到右都必须有默认值
int func2(int a,int b=10,int c=10){
return a+b;
}
//如果函数声明有默认参数,函数实现就不能有默认参数
//声明和实现只能有一个又默认参数
int func3(int a = 10,int b = 10);
int func3(int a,int b=10,int c=10){
return a+b;
}
int main(){
//如果我们自己传入数据,就用自己的数据,如果没有,那么用默认值
func(10,20);
}
函数的占位参数
C++中函数的形参列表中可以有占位参数,用来做占位,调用函数时必须填补该位置
(占位参数还可以有默认参数)
语法:返回值类型 函数名(数据类型){ }
//占位参数
void func(int a,int ){
cout << "this is func" <<endl;
}
//占位参数还可以有默认参数
void func1(int a,int = 10){
cout << "this is func" <<endl;
}
int main(){
func(10,10);
func1(10);
}
函数重载
函数重载基本语法
1、作用:函数名可以相同,提高复用性
2、函数重载满足条件:
①同一个作用域下
②函数名称相同
③函数参数类型不同 或者 个数不同 或者 顺序不同
3、注意:函数返回值不可以作为函数重载的条件
void func(){
cout << "func的调用"<<endl;
}
void func(int a){
cout << "func(int a)的调用"<<endl;
}
void func(double a){
cout << "func的调用(double a)"<<endl;
}
void func(int a,double b){
cout << "func的调用(int a,double b)"<<endl;
}
void func(double a,int b){
cout << "func的调用(double a,int b)"<<endl;
}
int main(){
func();
func(10);
func(3.14);
func(10,3.14);
func(3.14,10);
}
函数重载注意事项
引用作为重载条件
函数重载碰到函数默认参数
//引用作为重载条件
void func(int &a){//int &a=10; 不合法
cout << "func的调用"<<endl;
}
void func(const int &a){//const int &a = 10;合法
cout << "func的调用"<<endl;
}
//函数重载碰到函数默认参数
void func1(int a,int b){
cout << "func1的调用"<<endl;
}
void func1(int a){
cout << "func1的调用"<<endl;
}
int main (){
int a = 10;
func(a);
func(10);
func1(10);//当函数重载碰到默认参数,出现二义性,报错,尽量避免这种情况
}
更多推荐


所有评论(0)