C++ 函数参数匹配
1 单个参数匹配
| void f(); |
| void f(int); |
| void f(int, int); |
| void f(double, double=3.14); |
| |
| int main() { |
| f(5.6); |
| return 0; |
| } |
candidate functions:函数名称相同(f1, f2, f3, f4 都是)。
viable functions:参数个数相同(排除f1, f3),且参数可以转换成相同类型(f2, f4都是viable function)。如果不存在viable functions,则编译器报参数不匹配错误(可以通过linting检查)。 最后决定参数类型是否匹配,如果匹配优先调用,不能则选择可以隐式转换成类型相同的函数。
2 多个参数匹配
| void f(); |
| void f(int); |
| void f(int, int); |
| void f(double, double=3.14); |
| |
| int main() { |
| f(42, 5.6); |
| return 0; |
| } |
condidate functions: f1, f2, f3, f4
viable functions: f3, f4
优先级: 精确匹配的参数个数越多优先级越高,参数个数相同优先级相同,如果存在多个最高优先级的函数,则报参数模糊错误。
参数类型转换
优先级:
- 精确匹配:包括类型相同, 数组和参数名转换为指针,忽略顶层const
- const 转换 (把非const实参传给const形参)
- promotion数据提升,如int->long, char->unsigned等
- 算术转换或者指针类型转换
- 类类型(class-type)转换,如string->bool
| void ff(int); |
| void ff(short); |
| void manip(long); |
| void manip(float); |
| |
| int main() { |
| ff('a'); |
| |
| manip(3.14); |
| return 0; |
| } |
const Arguments
忽略顶层const, 原因是传参的时候实际上进行的是copy过程,即copy一份实参给形参,copy会忽略顶层const
| void f(int a); |
| void f(const int a); |
| void f(int *a); |
| void f(int* const a); |
const 转换
| void f(int &); |
| void f(const int &); |
| |
| int main() { |
| const int a{0}; |
| int b{0}; |
| f(a); |
| f(b); |
| return 0; |
| } |
另外,
| void f(int); |
| void f(int &); |
| |
| int main() { |
| int i = 0; |
| f(i); |
| return 0; |
| } |