函数重载

函数多态就是函数重载,函数重载的关键是函数的参数列表,也成为 函数特征标

如果两个函数的参数数目和类型相同,同时参数的排列顺序也相同,则它们的特征标相同

1
2
3
4
5
void print(double d, int width) // #1
void print(long l, int width); // #2

unsigned int year = 3210;
print(year, 6) // ambiguous call

如果只有 #2 原型,那函数调用会把 year 转换为 double 类型,但是上面有 2 个将数字作为第一个参数的原型,所以会拒绝函数调用

1
2
double cube(double x);
double cube(double & x);

类型引用和类型本身视为同一个特征标,所以也无法对上面两个进行匹配

非 const 实参可以传递给 const 形参,但 const 实参不能传递给非 const 形参

返回类型可以不同,但特征标必须也不同

1
2
3
4
5
6
7
8
9
void stove(double &r1);
void stove(const double &r2);
void stove(double &&r3);

double x = 75.1;
const double y = 32.0;
stove(x); // calls stove(double &)
stove(y); // calls stove(const double &)
stove(x+y); // calls stove(double &&)

如果没有定义 stove(double &&)stove(x+y) 将调用函数 stove(const double &)