函式多載是 C++ 核心特性,但你知道編譯器如何消除同名衝突?如何在調用點精確匹配最佳候選函式?本文從反組譯、標準草案、編譯器實作三個維度,完整還原多載機制。
print_int/print_string)、構造函式同名必要性、運算子多載本質即函式多載。void print(int) → _Z5printi
void print(string) → _Z5printSs
void print(long) → _Z5printl
void print(char) → _Z5printc
Mangled Name = 返回型別編碼 + 函式名 + 參數型別編碼序列
_Z:GCC 多載標記5print:長度 5 的名稱 "print"i/l/c/Ss:int/long/char/std::string 對應編碼_ZN4test5printEi(N4test = namespace/class test)若返回型別參與多載,調用點無法獨立於上下文解析:
float sqrt(float);
double sqrt(double);
void f(double da, float fl) {
float fl = sqrt(da); // 若依返回型別區分,此處無法確定調用哪個
double d = sqrt(da);
}
C++ 規定多載解析不依賴返回型別,保證調用解析的上下文獨立性。
void print(int); void print(double); void print(char);
print('a'); // 精確匹配 char
print(49); // 精確匹配 int
print(0); // 精確匹配 int (非指標)
print(3.14); // 精確匹配 double
print('a'+1); // 提升 char→int 匹配 int
void f1(char); void f1(long);
void f2(char*); void f2(int*);
void k(int i) {
f1(i); // 錯誤:int→char (標準轉換) vs int→long (提升) 同屬標準轉換等級
f2(0); // 錯誤:0 可轉 char* 或 int*
}

張素琴等人設計:

+ 用於 int/float/string,算運算子多載嗎?C 中 + 用於 int/float 算嗎?