基礎知識
函式必須先被宣告,然后才能被呼叫(被使用),函式的宣告讓編譯器得以檢查后續出現的使用方式是否正確——是否有足夠的引數、引數型別是否正確,等等,函式宣告不必提供函式體,但必須指明回傳型別、函式名,以及引數串列,此即所謂的函式原型(function prototype),
如果函式的回傳型別不為void,那么它必須在每個可能退出點上將值回傳,函式中的每條return陳述句都被用來明確表示該處就是函式的退出點,如果函式體最后一條陳述句不是return,那么最后一條陳述句之后便是該函式的隱式退出點,
當我們以by reference方式將物件作為函式引數傳入時,物件本身不會復制出另一份——復制的是物件的地址,函式中對該物件進行的任何操作,都相對于是對傳入的物件進行間接操作,將引數宣告為reference的理由之一是,希望得以直接對所傳入的物件進行修改;第二個理由是,降低復制大型物件的額外負擔,
我們也可以使用pointer形式傳遞函式引數,這和以reference傳遞的效果相同:傳遞的是物件的地址,而不是整個物件的副本,但是兩者用法不同,pointer引數和reference引數之間更重要的差異是,pointer可能(也可能不)指向某個實際物件,當我們提領pointer時,一定要先確定其值并非0,至于reference,則必定會代表某個物件,所以不需要做此檢查,
但使用delete釋放heap(堆,動態記憶體)分配而來的物件是,無需檢驗指標為零,編譯器會自動進行這項檢查,如果因為某種原因,程式員不想使用delete運算式,由heap分配而來的物件就永遠不會被釋放,這稱之為memory leak(記憶體泄漏),
在選擇函式引數使用pointer還是reference時,我們要知道,pointer可以被設定為0,表示未指向任何一個物件,而reference一定得代表某個物件,無法被設定為0,
將函式宣告為inline,表示要求編譯器在每個函式呼叫點上,將函式的內容展開,面對一個inline函式,編譯器可將該函式的呼叫操作改為以一份函式代碼副本代替,這將使我們獲得性能改善,將函式指定為inline,只是對編譯器提出的一種要求,而沒有強制性,編譯器是否執行這項請求,需視編譯器情況而定,
函式多載機制(function overloading),引數串列不相同(可能是引數型別不同,可能是引數個數不同)的兩個或多個函式,可以擁有相同的函式名稱,編譯器會將呼叫者提供的實際引數拿來和每個多載函式的引數對比,找出其中最合適的,編譯器無法根據函式回傳型別來區分兩個具有相同名稱的函式,因為回傳型別無法保證提供給我們一個足以區分不同多載函式的語境,
函式的定義只能有一份,可以有許多份宣告,我們不把函式的定義放入頭檔案,因為同一個程式的多個代碼檔案可能都會包含這個頭檔案,“只定義一份”的規則例外:inline函式的定義,為了能擴展inline函式的內容,在每個呼叫點上,編譯器都取得其定義,這意味著我們必須將inline函式的定義放在頭檔案,而不是把它放在各個不同的程式代碼檔案中;const object和inline函式一樣,是“只定義一份”規則下的例外,const object的定義只要一出檔案之外便不可見,這意味著我們可以在多個程式代碼檔案中加以定義,不會導致任何錯誤,(注意指向const object 的指標,其本身可能并不是const object)
在參考頭檔案時,如果頭檔案和包含此程式代碼檔案位于同一個磁盤目錄下,我們便使用雙引號,如果在不同的磁盤目錄下,我們便使用尖括號,更有技術含量的回答是,如果此檔案被認定為標準的或專案專屬的頭檔案,我們便以尖括號將檔案名括住,編譯器搜索此檔案時,會先在某些默認的磁盤目錄中尋找;如果檔案名由成對的雙引號括住,此檔案便被認為是一個用戶提供的頭檔案,搜索此檔案時,會由包含此檔案的檔案所在磁盤目錄開始找起,
練習題答案
練習2.1 先前的main()只讓用戶輸入一個位置值,然后便結束程式,如果用戶想取得兩個甚至更多元素值,它必須執行這個程式兩次或多次,請改寫main(),使它允許用戶不斷輸入位置值,直到用戶希望停止為止,
fibon_elem.h bool fibon_elem(int pos, int& elem) { if (pos <= 0 || pos > 45) { elem = 0; return false; } elem = 1; int n_2 = 1, n_1 = 1; for (int ix = 3;ix <= pos;++ix) { elem = n_2 + n_1; n_2 = n_1; n_1 = elem; } return true; } #include <iostream> #include "fibon_elem.h" using namespace std; extern bool fibon_elem(int, int&); int main() { int pos, elem; char ch; bool more = true; while (more) { cout << "Please enter a position: "; cin >> pos; if (fibon_elem(pos, elem)) { cout << "element # " << pos << " is " << elem << endl; } else { cout << "Sorry. Counld not calculate element # " << pos << endl; } cout << "would you like to try again? (y/n) "; cin >> ch; if (ch != 'y' && ch != 'Y') { more = false; } } return 0; }
練習2.2 Pentagonal數列的求值公式是P(n)=n(3n-1)/2,借此產生1,5,12,22,35等元素值,試定義一個函式,利用上述公式,將產生的元素放到用戶傳入的vector之中,元素個數由用戶指定,請檢查元素個數的有效性(太大可能引發overflow問題),接下來撰寫第二個函式,能夠將給定的vector的所有元素一一列印出來,此函式的第二引數接受一個字串,表示存放在vector內的數列的型別,最后再寫一個main(),測驗上述兩個函式,
#include <iostream> #include <vector> #include <string> using namespace std; bool calc_elements(vector<int>& vec, int pos); void display_elems(vector<int>& vec, const string& title, ostream& os = cout); int main() { vector<int> pent; int pos; const string title("Pentagonal Numeric Series"); cout << "Please enter a position: "; cin >> pos; if (calc_elements(pent, pos)) { display_elems(pent, title); } return 0; } bool calc_elements(vector<int>& vec, int pos) { if (pos <= 0 || pos > 100) { cerr << "Sorry. Invaild position: " << pos << endl; return false; } for (int ix = vec.size() + 1;ix <= pos;++ix) { vec.push_back(ix * (3 * ix - 1) / 2); } return true; } void display_elems(vector<int>& vec, const string& title, ostream& os) { os << '\n' << title << "\n"; for (int ix = 0;ix < vec.size();++ix) { os << vec[ix] << '\t'; if ((ix + 1) % 10 == 0) { cout << endl; } } os << endl; }
練習2.3 將練習2.2的Pentagonal數列求值函式拆分為兩個函式,其中之一為inline,用來檢驗元素個數是否合理,如果的確合理,而且尚未被計算,便執行第二個函式,執行實際的求值作業,
#include <iostream> #include <vector> #include <string> using namespace std; void really_calc_elems(vector<int>& , int ); inline bool calc_elems(vector<int>&, int); void display_elems(vector<int>& vec, const string& title, int, ostream& os = cout); int main() { vector<int> pent; int pos; char ch; bool more = true; const string title("Pentagonal Numeric Series"); while (more) { cout << "Please enter a position: "; cin >> pos; if (calc_elems(pent, pos)) { display_elems(pent, title, pos); } cout << "would you like to try again? (y/n) "; cin >> ch; if (ch != 'y' && ch != 'Y') { more = false; } } return 0; } inline bool calc_elems(vector<int>& vec, int pos) { if (pos <= 0 || pos > 100) { cerr << "Sorry. Invalid position: " << pos << endl; return false; } if (vec.size() < pos) { really_calc_elems(vec, pos); } return true; } void really_calc_elems(vector<int>& vec, int pos) { for (int ix = vec.size() + 1;ix <= pos;++ix) { vec.push_back((ix * (3 * ix - 1) / 2)); } } void display_elems(vector<int>& vec, const string& title, int pos, ostream& os) { os << '\n' << title << "\n"; for (int ix = 0;ix < pos;++ix) { os << vec[ix] << '\t'; if ((ix + 1) % 10 == 0) { cout << endl; } } os << endl; }
練習2.4 寫一個函式,以區域靜態(local static)的vector儲存Pentagonal數列元素,此函式回傳一個const指標,指向該vector,如果vector的大小小于指定的元素個數,就擴充vector的大小,接下來再實作第二個函式,接受一個位置值,回傳該位置上的元素,最后,撰寫main()測驗這些函式,
#include <iostream> #include <vector> using namespace std; inline bool check_validity(int pos); const vector<int>* pentagonal_series(int pos); bool pentagonal_elem(int pos, int& elem); int main() { int pos, elem; char ch; bool more = true; while (more) { cout << "Please enter a position: "; cin >> pos; if (pentagonal_elem(pos, elem)) { cout << "element " << pos << " is " << elem << endl; } cout << "would you like to continue? (y/n) "; cin >> ch; if (ch != 'y' && ch != 'Y') { more = false; } } return 0; } inline bool check_validity(int pos) { return (pos <= 0 || pos > 100) ? false : true; } const vector<int>* pentagonal_series(int pos) { static vector<int> _elems; if (check_validity(pos) && (pos > _elems.size())) { for (int ix = _elems.size() + 1;ix <= pos;++ix) { _elems.push_back((ix * (3 * ix - 1)) / 2); } } return &_elems; } bool pentagonal_elem(int pos, int& elem) { if (!check_validity(pos)) { cout << "Sorry. Invalid position: " << pos << endl; elem = 0; return false; } const vector<int>* pent = pentagonal_series(pos); elem = (*pent)[pos - 1]; return true; }
練習2.5 實作一個多載的max()函式,讓它接受以下引數:(a)兩個整數,(b)兩個浮點數,(c)兩個字串,(d)一個整數vector,(e)一個浮點數vector,(f)一個字串vector,(g)一個整陣列,以及一個表示陣列大小的整數值,(h)一個浮點陣列,以及一個表示陣列大小的整數值,(i)一個字串陣列,以及一個表示陣列大小的整數值,最后,撰寫main()測驗這些函式,
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; inline int max(int t1, int t2) { return t1 > t2 ? t1 : t2; } inline float max(float t1, float t2) { return t1 > t2 ? t1 : t2; } inline string max(string t1, string t2) { return t1 > t2 ? t1 : t2; } inline int max(const vector<int>& vec) { return *max_element(vec.cbegin(), vec.cend()); } inline float max(const vector<float>& vec) { return *max_element(vec.cbegin(), vec.cend()); } inline string max(const vector<string>& vec) { return *max_element(vec.cbegin(), vec.cend()); } inline int max(const int* parray, int size) { return *max_element(parray, parray + size); } inline float max(const float* parray, int size) { return *max_element(parray, parray + size); } inline string max(const string* parray, int size) { return *max_element(parray, parray + size); } int main() { int size = 5; int n = 1, n2 = 9; float f = 0.34, f2 = 9.3; string s = "dfsdg", s2 = "dafsdfsad"; vector<int> ivec = { 12,70,2,169,1,5,29 }; vector<float> fvec = { 2.5,24.8,18.7,4.1,23.9 }; vector<string> svec = { "we","were","her","pride","of","ten" }; int iarray[5] = { 1,2,3,4,5 }; float farray[5] = { 5.0,4.0,3.0,2.0,1.0 }; string sarray[5] = { "a","b","c","asfs","aaa" }; cout << "max(n,n2)=" << max(n, n2) << "\n" << "max(f,f2)=" << max(f, f2) << "\n" << "max(s,s2)=" << max(s, s2) << "\n" << "max(ivec)=" << max(ivec) << "\n" << "max(fvec)=" << max(fvec) << "\n" << "max(svec)=" << max(svec) << "\n" << "max(iarray,size)=" << max(iarray, size) << "\n" << "max(farray,size)=" << max(farray, size) << "\n" << "max(sarray,size)=" << max(sarray, size) << "\n"; return 0; }
練習2.6 以template重新完成練習2.5,并對main()函式做適當的修改,
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; template <typename Type> inline Type new_max(Type t1, Type t2) { return t1 > t2 ? t1 : t2; } template <typename elemType> inline elemType new_max(const vector<elemType>& vec) { return *max_element(vec.cbegin(), vec.cend()); } template <typename arrayType> inline arrayType new_max(const arrayType* parray, int size) { return *max_element(parray, parray + size); } int main() { int size = 5; int n = 1, n2 = 9; float f = 0.34, f2 = 9.3; string s = "dfsdg", s2 = "dafsdfsad"; vector<int> ivec = { 12,70,2,169,1,5,29 }; vector<float> fvec = { 2.5,24.8,18.7,4.1,23.9 }; vector<string> svec = { "we","were","her","pride","of","ten" }; int iarray[5] = { 1,2,3,4,5 }; float farray[5] = { 5.0,4.0,3.0,2.0,1.0 }; string sarray[5] = { "a","b","c","asfs","aaa" }; cout << "max(n,n2)=" << new_max(n, n2) << "\n" << "max(f,f2)=" << new_max(f, f2) << "\n" << "max(s,s2)=" << new_max(s, s2) << "\n" << "max(ivec)=" << new_max(ivec) << "\n" << "max(fvec)=" << new_max(fvec) << "\n" << "max(svec)=" << new_max(svec) << "\n" << "max(iarray,size)=" << new_max(iarray, size) << "\n" << "max(farray,size)=" << new_max(farray, size) << "\n" << "max(sarray,size)=" << new_max(sarray, size) << "\n"; return 0; }
end,
“紙上得來終覺淺,絕知此事要躬行,”
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/69122.html
標籤:C++
