ToB企服应用市场:ToB评测及商务社交产业平台

标题: C++函数参数匹配规则 [打印本页]

作者: 雁过留声    时间: 2023-8-29 15:26
标题: C++函数参数匹配规则
C++ 函数参数匹配

1 单个参数匹配
  1. void f(); //f1
  2. void f(int); //f2
  3. void f(int, int); //f3
  4. void f(double, double=3.14);//f4
  5. int main() {
  6.     f(5.6); //调用f4
  7.     return 0;
  8. }
复制代码
candidate functions:函数名称相同(f1, f2, f3, f4 都是)。
viable functions:参数个数相同(排除f1, f3),且参数可以转换成相同类型(f2, f4都是viable function)。如果不存在viable functions,则编译器报参数不匹配错误(可以通过linting检查)。 最后决定参数类型是否匹配,如果匹配优先调用,不能则选择可以隐式转换成类型相同的函数。
2 多个参数匹配
  1. void f(); //f1
  2. void f(int); //f2
  3. void f(int, int); //f3
  4. void f(double, double=3.14);//f4
  5. int main() {
  6.     f(42, 5.6); //报错,参数模糊
  7.     return 0;
  8. }
复制代码
condidate functions: f1, f2, f3, f4
viable functions: f3, f4
优先级: 精确匹配的参数个数越多优先级越高,参数个数相同优先级相同,如果存在多个最高优先级的函数,则报参数模糊错误。
参数类型转换

优先级:
Promotion and Arithmetic Conversion
  1. void ff(int); //f1
  2. void ff(short); //f2
  3. void manip(long); //f3
  4. void manip(float); //f4
  5. int main() {
  6.     ff('a'); //调用f1,char -> int是promotionO(比int短的数据类型统一promotion为int,
  7.              // char->short 是算术转换
  8.     manip(3.14); //error: ambiguous call,3.14视为double,double->float和doule->long在优先级上是等价的
  9.     return 0;
  10. }
复制代码
const Arguments

忽略顶层const, 原因是传参的时候实际上进行的是copy过程,即copy一份实参给形参,copy会忽略顶层const
  1. void f(int a);
  2. void f(const int a);//报错,重复定义,两者只能定义一种
  3. void f(int *a);
  4. void f(int* const a);//报错,重复定义,两者只能定义一种
复制代码
const 转换
  1. void f(int &); //f1
  2. void f(const int &);//f2
  3. int main() {
  4.     const int a{0};
  5.     int b{0};
  6.     f(a); //调用f2(精确匹配)
  7.     f(b); //调用f1(没有定义f1时,调用f2)
  8.     return 0;
  9. }
复制代码
另外,
  1. void f(int);
  2. void f(int &);
  3. int main() {
  4.     int i = 0;
  5.     f(i); //报错,ambiguous call
  6.     return 0;
  7. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4