# C++ 函數參數匹配 ## 1 單個參數匹配 ```C++ void f(); //f1 void f(int); //f2 void f(int, int); //f3 void f(double, double=3.14);//f4 int main() { f(5.6); //調用f4 r ...
C++ 函數參數匹配
1 單個參數匹配
void f(); //f1
void f(int); //f2
void f(int, int); //f3
void f(double, double=3.14);//f4
int main() {
f(5.6); //調用f4
return 0;
}
candidate functions:函數名稱相同(f1, f2, f3, f4 都是)。
viable functions:參數個數相同(排除f1, f3),且參數可以轉換成相同類型(f2, f4都是viable function)。如果不存在viable functions,則編譯器報參數不匹配錯誤(可以通過linting檢查)。 最後決定參數類型是否匹配,如果匹配優先調用,不能則選擇可以隱式轉換成類型相同的函數。
2 多個參數匹配
void f(); //f1
void f(int); //f2
void f(int, int); //f3
void f(double, double=3.14);//f4
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
Promotion and Arithmetic Conversion
void ff(int); //f1
void ff(short); //f2
void manip(long); //f3
void manip(float); //f4
int main() {
ff('a'); //調用f1,char -> int是promotionO(比int短的數據類型統一promotion為int,
// char->short 是算術轉換
manip(3.14); //error: ambiguous call,3.14視為double,double->float和doule->long在優先順序上是等價的
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 &); //f1
void f(const int &);//f2
int main() {
const int a{0};
int b{0};
f(a); //調用f2(精確匹配)
f(b); //調用f1(沒有定義f1時,調用f2)
return 0;
}
另外,
void f(int);
void f(int &);
int main() {
int i = 0;
f(i); //報錯,ambiguous call
return 0;
}
本文來自博客園,作者:小魚上岸,轉載請註明原文鏈接:https://www.cnblogs.com/yucongxing/p/cpp_function_argument_match_regular.html