目录
1,函数重载
函数重载是一种泛型设计,c语言和python都不支持,c++支持
2,普通函数重载
函数签名由函数名和函数参数组成,和返回值无关。
签名相同的函数放一起会造成符号冲突,无法编译:
如果两个同名函数的签名不同(即参数不同),那么就可以重载:
void f(int x)
{
cout << x << " ";
}
void f(double x)
{
cout << x << " ";
}
string f(string s)
{
return "";
}
int main()
{
f(1);
f(1.2);
f("");
return 0;
}
3,重载歧义
(1)相似类型的重载歧义
#include<iostream>
using namespace std;
void f(float x)
{
cout << x << " ";
}
void f(double x)
{
cout << x+1 << " ";
}
int main()
{
//f(1)
f(float(1));
f(double(1));
f(1.0);
return 0;
}
float和double都是实数类型,如果参数是1,那么无法自动推导类型,编译失败。
如果指明了1的类型,或者入参是1.0,那么可以推导出类型。
#include<iostream>
using namespace std;
void f(int x,double y)
{
cout << x << " ";
}
void f(double x,int y)
{
cout << x+1 << " ";
}
int main()
{
//f(1, 2);
f(1.0, 2);
//f(1, int(2));
f(1, double(2));
return 0;
}
类似的,在这个代码中,f(1,2)也有重载歧义,如果只把2指明为int还是不行,指明为double才没有歧义。
(2)右值的类型推导歧义
void f(int a,int b)
{
cout << 111;
return;
}
void f(double a,double b)
{
cout << 222;
return;
}
int main()
{
f(1, 2.5);
return 0;
}
右值1会直接推导成int,所以没有合适的重载版本。
4,类成员函数重载
类的成员函数,重载规则和普通函数一致。
构造函数也可以重载,析构函数不能重载。
5,模板
6,重载优先级
从最佳到最差分四大类:
- 完全匹配(常规函数优于模板函数)
- 提升转换(char转int,float转double)
- 标准转换(int转char,long转double)
- 自定义转换