函数重载:
当定义多个函数名相同时,编译器通过函数的参数列表中的参数个数和参数类型进行识别。(函数重载必须在同一作用域下)
void fun(int a ,int b){
cout << a << ',' << b << endl;
}
void fun(double a ,double b){
cout << a << ',' << b << endl;
}
int main(){
fun(1,2); //输出结果为1,2;
fun(1.1,2.2); //输出结果为1.1,1.2;
return 0;
}
编译器在编译时会将函数编译成函数名+参数列表的形式以区分函数重名问题。
二义性:
1.当重载函数的参数类型相同但参数个数不同时,对于传递参数的个数存在二义性。
void fun(int a = 10, int b = 20 , int c = 30);
void fun(int a = 10, int b = 20 );
int main() {
fun(10); //编译不通过存在二义性。
system("pause");
return 0;
}
void fun(int a,int b,int c) {
cout << a << ',' << b << ',' << c << endl;
}
void fun(int a, int b) {
cout << a << ',' << b << endl;
}
2.参数个数相同,仅参数名称不同。