標籤:size main函數 style 對象傳遞 foo 重載函數 end 參數 一個
函數重載
如果同一範圍內的幾個函數名字相同但形參列表不同,我們稱之為重載函數。
void print(const char *cp);void print(const int *beg, const int *end);void print(const int ia[], size_t size);int j[2] = {0,1};print("Hello World!");print(j, end(j) - begin(j));print(begin(j), end(j));
main函數不能重載
對於重載函數來說,它們應該在形參數量或形參類型上有所不同。
不允許兩個函數除了傳回型別外其他所有的要素都相同。
有時候兩個形參列表看起來不一樣,實際上是相同的
int calc(const int &a);int calc(const int&);
形參名只是起到了協助記憶的作用。有沒有它並不影響形參列表的內容
重載和const形參
頂層const不影響傳入函數的對象。一個擁有頂層const的形參無法和另一個沒有頂層const的形參區分開
Record lookup(Phone);Record lookup(const Phone);Record lookup(Phone*);Record lookup(Phone* const);
以上函數存在重複聲明
如果形參是某種類型的指標或引用,則通過區分其指向的是常量對象還是非常量對象可以實現函數重載,此時const是底層的
Record lookup(Account&);// 函數範圍Account的引用Record lookup(const Account&);// 函數作用於常量引用Record lookup(Account*);// 作用於指向Account指標Record lookup(const Account*);// 作用於指向常量的指標
我們只能把const對象傳遞給const形參,
相反的,非常量可以轉換成const
所以以上4個函數都能作用於非常量對象或者指向非常量對象的指標。
當我們傳遞一個非常量對象或者指向非常量對象的指標使,編譯器會優先選用非常量版本的函數。
const_cast和重載
比較兩個string對象的長度,並返回較短的那個引用
const string &shorterString(const string &s1, const string &s2){ return s1.size() < s2.size() ? s1 : s2;}
我們可以對兩個非常量的string實參調用這個函數,但返回的結果是const string的引用。
所以我們需要一個新的函數,當實參不是常量時,得到的結果是一個普通的引用。可以使用const_cast完成。
string &shorterString(string &s1, string &s2) { auto &r = shorterString(const_cast<const string>(s1), const_cast<const string>(s2)); return const_cast<string&>(r);}
首先將實參強制轉換成對const的引用,然後調用shorterString的const版本,const版本返回對const string的引用,然後將其轉換成一個普通的string&。
重載與範圍
一般來說,將函式宣告置於局部範圍內不是一個明智的選擇。
重載對範圍的一般性質並沒有改變,如果我們在內層範圍中聲明名字,它將隱藏外層範圍中聲明的同名實體。在不同範圍中無法重載函數名
在範圍中調用函數時,編譯器首先尋找對該函數名的聲明,一旦在該範圍內找到所需名字,編譯器會自動忽略外層範圍中的同名實體。剩下來就是檢查函數調用是否有效了。
在C++中,名字尋找在類型檢查之前
string read();void print(const string &);void print(double);void fooBar(int ival){ bool read = false; // 新範圍,隱藏了外層read函數 string s = read(); // 錯誤,read是bool類型變數 void print(int); // 在範圍內聲明函數 print("Value: "); // 錯誤,範圍內只有print(int),外層print被隱藏 print(ival); // 正確,調用當前print(int) print(3.14); // 正確,調用當前print(int).}
void print(const string &);void print(double);void print(int);void fooBar2(int ival) { print("Value: "); // 重載調用 print(ival); // 重載調用 print(3.14); // 重載調用,void print(double)}
void print(const string &);void print(double);void print(int);void fooBar2(int ival) { print("Value: "); // 重載調用 print(ival); // 重載調用 print(3.14); // 重載調用,void print(double)}
[C++] 函數重載