函数重载(overload)
一个类中,函数名相同,参数列表不同[1]
- [1]参数列表不同,可以是参数顺序不同
- [2]返回值不同不构成重载条件
- [3]const修饰同样可以构成重载,因为const相当于static this
重载与自动类型转换(auto-cast)
当调用重载函数时,不会进行自动类型转换,需要调用者明确参数类型。
#include <iostream>
using namespace std;
void f(double d)
{
cout << "double " << d << endl;
}
void f(short i)
{
cout << "short " << i << endl;
}
int main(int argc, char const *argv[])
{
f('a'); //need auto-cast, illegal
f(2); //need auto-cast, illegal
f(2L); //need auto-cast, illegal
f(3.2); //默认3.2为double,调用f(double d)
return 0;
}
默认参数(Default arguments)
一般情况下,不要使用默认参数。
默认参数需要写在参数表的最右端,可以有多个。
int f(int a, int b=1, int c); //illeagle
默认参数写在.h中的原型中,而且不能在.cpp中重复写默认参数。 在编译过程中,编译器会自动传入默认参数值(写死)。默认函数是编译阶段的事,不是运行阶段的事。