红魔咖啡馆

头发越掉越多,头发越掉越少

0%

【C++】高阶函数

高阶函数

函数的默认参数

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){ // const int 与int 类型不同
  cout << "invoke f(const int &"<<a<< ')'<<endl;
}

int main(){
  // 根据传入的参数执行对应函数
  f2(a); // 调用了无const的
  f2(10); // 调用了有const的
  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(){
  //f3(10); // 会出错,出现二义性
  return 0;

}