1.函数重载概述
作用:函数名可以相同,提高复用性
满足的条件:
- 同一个作用域下
- 函数名相同
- 函数参数类型不同,或者个数不同或者顺序不同
- 注意:函数的返回值不可以作为函数重载的条件
2.函数重载的注意事项
-
引用作为重载条件
- 函数重载遇到函数默认参数
-
#include <iostream> using namespace std; void fun(int &a) //int &a = 10 ;不是合法的 { cout << "fun1" << endl; } void fun(const int &a) //int temp = 10; const int&a = temp; 合法 { cout << "fun2" << endl; } void fun2(int a, int b =10) { cout<< "fun3" << endl; } void fun2(int a) { cout<<"fun4" << endl; } int main() { int a = 10; fun(a); //fun1 加上const变成只读 fun(10); //fun2 fun2(10); //碰到默认参数会引起歧义,需要避免 return 0; }