高阶函数
函数的默认参数
C++中,形参是可以有缺省值的
注:
- 若某个位置已经有了缺省值,则从该位置之后往后都必须要有缺省值
- 若函数声明有缺省值,则函数实现就不能有缺省值 (二义性)
1 2 3 4 5 6 7 8 9 10 11
| #include <iostream> using namespace std; int f(int a, int b = 20, int c = 30){ return a+b+c; } int main(){ cout << f(10)<<endl; cout << f(10, 30)<<endl; return 0;
}
|
函数的占位参数
C++中函数的形参列表中可以有占位参数,调用时必须填补该位置
语法:<返回值类型> <函数名>([数据类型]){}
注:
- 目前占位参数传入的参数无法使用
- 占位参数可以有缺省值
1 2 3 4 5 6 7 8
| #include <iostream> using namespace std; void f(int a, int){ cout << a <<" occupation"<<endl; } int main(){ f(10, 10); }
|
函数重载
作用:函数名可以相同,用于提高复用性
满足条件:
- 同一个作用域下
- 函数名相同
- 函数参数类型,个数,顺序不同
函数返回值类型不可以做为函数重载的条件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| #include <iostream> using namespace std;
void f(){ cout << "invoke f"<<endl; } void f(int a){ cout << "invoke f(int "<<a<<')'<<endl; } void f(double a){ cout << "invoke f(double "<<a<<')'<<endl; } void f(double a, int b){ cout << "invoke f(double "<<a<<", int "<<b << ')'<<endl; } void f(int a, double b){ cout << "invoke f(int "<<a<<", double "<<b << ')'<<endl; }
int main(){ f(); f(10); f(3.14); f(10,3.14); f(3.14,10); return 0;
}
|
1 2 3 4 5
| invoke f invoke f(int 10) invoke f(double 3.14) invoke f(int 10, double 3.14) invoke f(double 3.14, int 10)
|
引用作为重载条件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| void f2(int &a){ cout << "invoke f(int &"<<a<< ')'<<endl; } void f2(const int &a){ cout << "invoke f(const int &"<<a<< ')'<<endl; }
int main(){ f2(a); f2(10); return 0;
}
|
- 11行相当于实现
int &b = a,是合法的
- 但若只传值,则11行相当于
int &a = 10,
是不合法的,此时12行相当于const int &a = 10,是合法的
缺省值与函数重载
当存在缺省值,使得调用函数传入参数个数和被重载的函数的传入参数个数一样时,会出现二义性,故报错
1 2 3 4 5 6 7 8 9 10 11 12
| void f3(int a){ cout << "invoke f3(int &"<<a<< ')'<<endl; } void f3(int a, int b = 10){ cout << "invoke f3(int &"<<a<< ") with b = 10"<<endl; } int main(){ return 0;
}
|