函數重載
若同一作用域內幾個函數名字相同但形參列表不同鸣个,可稱之為重載函數。在調用這些函數時編譯器會根據實參類型推斷:
void print(const char* cp);
print("Hello");
void print(const int* beg, const int* end);
print(j, end(j)-begin(j));
void print(const int ia[], size_t size);
print(begin(j), end(j))
定義重載函數
不允許定義兩個含有相同參數列表但返回類型不同的函數。
判斷形參類型是否相異
允許存在形參列表不同但實際相同的函數:
int a(const int& i);
int a(const int&);
int a(const int* i);
int a(const int* j);
重載和const形參
頂層const不影響傳入函數的對象对粪,一個含有頂層const的形參和同名非const形參不做區(qū)分:
int a(const int i);
int a(int i); //重復定義
若形參是復合類型仿吞,則const作為底層const可被區(qū)分:
int a(const int& i);
int a(int& i); //合理
int a(const int* i);
int a(int* i); //合理
const_cast和重載
const_cast在重載函數的情況下最有用。例如:
const string &shorterString(const string& s1, const string& s2{
return s1.size() <= s2.size() ? s1 : s2;
}
該函數只能接受const string類型的實參并且將其返回淳地,而為了實現對非const類型的支持怖糊,可以通過以下方式重載;
const string &shorterString(string& s1, string& s2){
// 將實參強制轉換后裝入接受兩個const的函數:
auto &r = shorterString(const_cast<const string&>(s1),
const_cast<const string&>(s2));
// 返回非const的類型:
return const_cast<string&>(r);
}
調用重載的函數
定義了一組重載函數后需要以合理的實參進行調用。
在函數匹配 function matching過程中把函數調用與一組重載函數中的某一個關聯(lián)起來颇象,函數匹配也叫做重載確定 overload resolution伍伤。編譯器首先將調用的實參與重載集合中每一個函數的形參進行比較,然后根據比較結果確定到底調用哪一個遣钳。
調用重載函數時的可能結果:
- 編譯器找到一個與實參的最佳匹配 best match扰魂,并生成調用代碼;
- 找不到任何可匹配的函數蕴茴,編譯器發(fā)出無匹配 no match的錯誤劝评;
- 二義性調用 ambiguous call 無最佳匹配同樣會報錯。
重載與作用域
如果在內層作用域聲明函數名倦淀,則外層作用域中聲明的同名實體將被隱藏
string read();
void print(const string&);
void print(double);
void foo(int val){
bool read = false; //內層聲明蒋畜,隱藏外層的read
string s = read(); //錯誤:read為bool值
void print(int); //新作用域,將之前的全部隱藏
print("Hello"); //自然會報錯
print(val); //正確撞叽,在該作用域中可見百侧。
}
C++中,名字查找發(fā)生在類型檢查之前能扒。