基礎知識
Class的定義由兩部分組成:class的宣告,以及緊接在宣告之后的主體,主體部分由一對大括號括住,并以分號結尾,主體內的兩個關鍵字public和private,用來標示每個塊的“member訪問權限”,Public member可以在程式的任何地方被訪問,private member只能在member function或是class friend內被訪問,
class的前置宣告(forward declaration),將class名稱告訴編譯器,并未提供此class的任何其他資訊(像class支持的操作行為及所包含的data member等),前置宣告使我們得以進行類指標(class pointer)的定義,或以此class作為資料型別,
所有member function都必須在class主體內進行宣告,至于是否同時進行定義,可自由決定,如果要在class主體內定義,這個member function會自動被視為inline函式,要在class主體之外定義member function,必須使用特殊的語法,目的在于分辨該函式究竟屬于哪一個class,使用雙冒號“::”,即所謂的class scope resolution(類作用域決議)運算子,
對于inline函式而言,定義與class主體內或主體外,并沒有什么分別,然而就像non-member-inline function一樣,它也應該放在頭檔案中,class定義一起inline member function通常都會被放在與class同名的頭檔案中,non-inline member function應該在程式代碼檔案中定義,該檔案通常與class同名,其后接著擴展名.C、.cc、.cpp或.cxx(x代表橫放的+),
初始化data member,魔法不會自動產生,編譯器不會自動為我們處理,如果我們提供一個或多個特別的初始化函式,編譯器就會在每次class object被定義出來時,呼叫適當的函式加以處理,這些特別的初始化函式稱為constructor(建構式),Constructor的函式必須與class名稱相同,語法規定,constructor不應指定回傳型別,亦不用回傳任何值,它可以被多載(overloaded),最簡單的constructor是所謂的default constructor,它不需要任何引數(argument),(沒有引數不需要加括號,加括號會將其解釋為一個函式,這是為了兼容C所致),
和constructor對立的是destructor,所謂destructor乃是用戶自定義的一個class member,一旦某個class提供有destructor,當其object結束生命時,便會自動呼叫destructor處理善后,Destructor主要用來釋放在constructor中或物件生命周期中分配的資源,Destructor的名稱有嚴格規定:class名稱再加上‘~’前綴,它絕對不會有回傳值,也沒有任何引數,由于其引數串列是空的,所以也絕不可能別多載(overloaded),Destructor并非絕對必要,我們沒有義務非得提供destructor,事實上,C++編程的最難部分之一,便是了解何時需要定義destructor而何時不需要,
當我們設計class時,必須問問自己,在此class之上進行“成員逐一初始化”的行為模式是否適當?如果答案肯定,我們就不需要另外提供copy constructor,如果答案否定的,我們就必須另行定義copy constructor,并在其中撰寫正確的初始化操作,如果有必要為某個class撰寫copy constructor,那么同樣有必要為它撰寫copy assignment operator,
static member function 可以在“與任何物件都無瓜葛”的情形之下呼叫,member function 只有在“不訪問任何non-static member”的條件下才能夠被宣告為static,宣告方式是在宣告之前加上關鍵字static,當我們在class主體外部進行member function的定義時,無需重復加上關鍵字static,這個規則也適用于static data member,
運算子多載規則:
- 不可以引入新的運算子,除了“.”、“.*”、“::”、“?:”四個運算子,其他運算子皆可被多載,
- 運算子的運算元(operand)個數不可以改變,每個二元運算子都需要兩個運算元,每個一元運算子都需要恰好一個運算元,因此,我們無法定義出一個equality運算子,并令它接受兩個以上或兩個以下的運算元,
- 運算子的優先級(precedence)不可改變,例如,除法的運算優先級永遠高于加法,
- 運算子函式的引數串列中,必須至少有一個引數為class型別,也就是說,我們無法為諸如指標之類的non-class型別,重新定義其原已存在的運算子,當然無法為它引進新的運算子,
對于increment遞增運算子(或遞減)的多載,分為前置和后置兩個版本,前置版的引數串列是空的,后置版的引數串列原本也應該時空,然而多載規則要求,引數串列必須獨一無二,因此,C++想出一個變通辦法,要求后置版得有一個int引數,int引數從何發生,又到哪里去,編譯器會自動會后置產生一個int引數(其值必為0),用戶不必為此煩惱,
所謂friend,具備了與class member function相同的訪問權限,可以訪問class的private member,只要在某個函式原型(prototype)前加上關鍵字friend,就可以將它宣告為某個class的friend,這份宣告可以出現在class定義的任意位置上,不受private或public的影響,如果你希望將數個多載函式都宣告為某個class的friend,必須明確地為每個函式加上關鍵字friend,
maximal munch編譯規則,此規則要求,每個符號序列(symbol seuqence)總是以“合法符號序列”中最長的那個解釋,因為>>是個合法的運算子序列,因此如果兩個>之間沒有空白,這兩個符號必定會被合在一起看待,同樣道理,如果我們寫下a+++p,它必定會被解釋為“a++ +p”,
練習題答案
練習4.1 建立Stack.h和Stack.suffix,此處的suffix是你的編譯器所能接受的擴展名,或是你的專案所使用的擴展名,撰寫main()函式,練習操作Stack的所有公開介面,并加以編譯執行,程式代碼檔案和main()都必須包含Stack.h:#include “Stack.h”
Stack.h #include <string> #include <vector> using namespace std; class Stack { public: bool push(const string&); bool pop(string& elem); bool peek(string& elem); bool empty() const { return _stack.empty(); } bool full() const { return _stack.size() == _stack.max_size(); } int size() const { return _stack.size(); } private: vector<string> _stack; }; Stack.cpp #include "Stack.h" bool Stack::pop(string& elem) { if (empty()) return false; elem = _stack.back(); _stack.pop_back(); return true; } bool Stack::peek(string& elem) { if (empty()) return false; elem = _stack.back(); return true; } bool Stack::push(const string& elem) { if (full()) return false; _stack.push_back(elem); return true; } main.cpp #include "Stack.h" #include <iostream> int main() { Stack st; string str; while (cin >> str && !st.full()) { st.push(str); } if (st.empty()) { cout << '\n' << "Oops: no strings were read -- bailing out\n "; return 0; } st.peek(str); if (st.size() == 1 && str.empty()) { cout << '\n' << "Oops: no strings were read -- bailing out\n "; return 0; } cout << '\n' << "Read in " << st.size() << " strings!\n" << "The strings, in reverse order: \n"; while (st.size()) { if (st.pop(str)) cout << str << ' '; } cout << '\n' << "There are now " << st.size() << " elements in the stack!\n"; }
練習4.2 擴展Stack功能,以支持find()和count()兩個操作,find()會查看某值是否存在而回傳true或false,count()回傳某字串的出現次數,重新實作練習4.1的main(),讓它呼叫這兩個函式,
Stack_2.h #include <string> #include <vector> using namespace std; class Stack { public: bool push(const string&); bool pop(string& elem); bool peek(string& elem); bool empty() const { return _stack.empty(); } bool full() const { return _stack.size() == _stack.max_size(); } int size() const { return _stack.size(); } bool find(const string& elem) const; int count(const string& elem) const; private: vector<string> _stack; }; Stack_2.cpp #include "Stack_2.h" #include <algorithm> bool Stack::pop(string& elem) { if (empty()) return false; elem = _stack.back(); _stack.pop_back(); return true; } bool Stack::peek(string& elem) { if (empty()) return false; elem = _stack.back(); return true; } bool Stack::push(const string& elem) { if (full()) return false; _stack.push_back(elem); return true; } bool Stack::find(const string& elem) const { vector<string>::const_iterator end_it = _stack.end(); return ::find(_stack.begin(), end_it, elem) != end_it; } int Stack::count(const string& elem) const { return ::count(_stack.begin(), _stack.end(), elem); } main.cpp #include "Stack_2.h" #include <iostream> int main() { Stack st; string str; while (cin >> str && !st.full()) { st.push(str); } if (st.empty()) { cout << '\n' << "Oops: no strings were read -- bailing out\n "; return 0; } st.peek(str); if (st.size() == 1 && str.empty()) { cout << '\n' << "Oops: no strings were read -- bailing out\n "; return 0; } cout << '\n' << "Read in " << st.size() << " strings!\n"; cin.clear(); //清除end-of-file的設定 cout << "what word to search for? "; cin >> str; bool found = st.find(str); int count = found ? st.count(str) : 0; cout << str << (found ? " is " : "isn't ") << "in the stack."; if (found) cout << "It occurs " << count << " times\n"; }
練習4.3 考慮以下所定義的全域(global)資料:
string program_name; string vector_stamp; int version_number; int tests_run; int tests_passed;
撰寫一個用以包裝這些資料的類,
#include <string> using std::string; class globalWrapper { public: static int tests_passed() { return _tests_passed; } static int tests_run() { return _tests_run; } static int version_number() { return _version_number; } static string version_stamp() { return _version_stamp; } static string program_name() { return _program_name; } static void tests_passed(int nval) { _tests_passed = nval; } static void tests_run(int nval) { _tests_run = nval; } static void version_stamp(const string&nstamp) { _version_stamp = nstamp; } static void version_number(int nval) { _version_number = nval; } static void program_name(const string& npn) { _program_name = npn; } private: static string _program_name; static string _version_stamp; static int _version_number; static int _tests_run; static int _tests_passed; }; string globalWrapper::_program_name; string globalWrapper::_version_stamp; int globalWrapper::_version_number; int globalWrapper::_tests_run; int globalWrapper::_tests_passed;
練習4.4 一份“用戶概況記錄(user profile)”內含以下資料:登陸記錄、實際姓名、登入次數、猜過次數、猜對次數、等級——包括初級、中級、高級、專家、以及猜對百分比(可實時計算獲得,或將其值儲存起來備用),請寫出一個名為UserProfile的class,提供以下操作:輸入、輸出、相等測驗、不等測驗,其constructor必須能夠處理默認的用戶等級、默認的登陸名稱(“guest”),對于同樣的名為guest的多個用戶,你如何保證每個guest有他自己獨有的登陸會話(login session),不會和其他人混淆?
UserProfile.h #include <iostream> #include <string> #include <map> using namespace std; class UserProfile { public: enum uLevel { Beginner, Intermediate, Advanced, Guru }; UserProfile(string login, uLevel = Beginner); UserProfile(); //default memberwise initilaization和default memberwise copy已足夠所需, //不必另行設計copy constructor或copy assignment operator, //也不需要destructor bool operator==(const UserProfile&); bool operator!=(const UserProfile& rhs); //以下函式用來讀取資料 string login()const { return _login; } string user_name() const { return _user_name; } int login_count() const { return _times_logged; } int guess_count() const { return _guesses; } int guess_correct() const{ return _correct_guesses; } double guess_average() const; string level() const; //以下函式用來寫入資料 void reset_login(const string& val) { _login = val; } void user_name(const string& val) { _user_name = val; } void reset_level(const string&); void reset_level(uLevel newlevel) { _user_level = newlevel; } void reset_login_count(int val) { _times_logged = val;} void reset_guess_count(int val) { _guesses = val; } void reset_guess_correct(int val) { _correct_guesses = val; } void bump_login_count(int cnt = 1) { _times_logged += cnt; } void bump_guess_count(int cnt=1) { _guesses = cnt; } void bump_guess_correct(int cnt = 1) { _correct_guesses = cnt; } private: string _login; string _user_name; int _times_logged; int _guesses; int _correct_guesses; uLevel _user_level; static map<string, uLevel> _level_map; static void init_level_map(); static string guest_login(); }; inline double UserProfile::guess_average() const { return _guesses ? double(_correct_guesses) / double(_guesses) * 100 : 0.0; } inline UserProfile::UserProfile(string login,uLevel level) :_login(login),_user_level(level), _times_logged(1), _guesses(0), _correct_guesses(0) {} #include <cstdlib> inline UserProfile::UserProfile() : _login("guest"), _user_level(Beginner), _times_logged(1), _guesses(0), _correct_guesses(0) { static int id = 0; char buffer[16]; //_itoa()是C標準庫所提供的的函式,會將整數轉換為對應的ASCII字串形式 _itoa(id++, buffer, 10); //針對guest,加入一個獨一無二的會話識別符號(session id) _login += buffer; } inline bool UserProfile:: operator==(const UserProfile& rhs) { if (_login == rhs._login && _user_name == rhs._user_name) return true; return false; } inline bool UserProfile::operator!=(const UserProfile& rhs) { return !(*this == rhs); } inline string UserProfile::level() const { static string _level_table[] = { "Beginner","Intermediate","Advanced","Guru" }; return _level_table[_user_level]; } //以下難度頗高,不過恰可作為示范 map<string, UserProfile::uLevel> UserProfile::_level_map; void UserProfile::init_level_map() { _level_map["Beginner"] = Beginner; _level_map["Intermediate"] = Intermediate; _level_map["Advanced"] = Advanced; _level_map["Guru"] = Guru; } inline void UserProfile::reset_level(const string& level) { map<string, uLevel>::iterator it; if (_level_map.empty()) init_level_map(); //確保level的確代表一個可識別的用戶等級 _user_level = ((it = _level_map.find(level)) != _level_map.end()) ? it->second : Beginner; } main.cpp #include "UserProfile.h" #include <iostream> ostream& operator <<(ostream& os, const UserProfile& rhs) { //輸出格式,如:stanl Beginner 12 100 10 10% os << rhs.login() << ' ' << rhs.level() << ' ' << rhs.login_count() << ' ' << rhs.guess_count() << ' ' << rhs.guess_correct() << ' ' << rhs.guess_average() << endl; return os; } istream& operator >>(istream& is, UserProfile& rhs) { //是的,以下假設所有輸入都有效,不做錯誤檢驗 string login, level; is >> login >> level; int lcount, gcount, gcorrect; is >> lcount >> gcount >> gcorrect; rhs.reset_login(login); rhs.reset_level(level); rhs.reset_login_count(lcount+10); rhs.reset_guess_count(gcount); rhs.reset_guess_correct(gcorrect); return is; } int main() { UserProfile anon; cout << anon; //測驗output運算子 UserProfile anon_too; //看看我們是否取得一份獨一無二的識別符號 cout << anon_too; UserProfile anna("Annal", UserProfile::Guru); cout << anna; anna.bump_guess_count(27); anna.bump_guess_correct(25); anna.bump_login_count(); cout << anna; cin >> anon; //測驗input運算子 cout << anon; return 0; }
練習4.5 請實作一個4*4的Martix class,至少提供以下介面:矩陣加法、矩陣乘法、列印函式print()、復合運算子+=,以及一組支持下標操作(subscripting)的function call運算子,像下面這樣:
float& operator()(int row, int cloumn); float operator()(int row, int cloumn) const;
請提供一個default constructor,可選擇地接受16個資料值,再提供一個constructor,可接受一個擁有16個元素的陣列,你不需要為此class 提供copy constructor,copy assignment operator、destructor,第六章重新實作Matrix class時才會需要這幾個函式,用以支持任意行列的矩陣,
Matrix.h #include <iostream> using namespace std; typedef float elemType; //方便我們轉為template class Matrix { //friend宣告不受訪問權限的影響 //我喜歡把它們放在class一開始處 friend Matrix operator+(const Matrix&, const Matrix&); friend Matrix operator*(const Matrix&, const Matrix&); public: Matrix(const elemType*); Matrix(const elemType = 0., const elemType = 0., const elemType = 0., const elemType = 0., const elemType = 0., const elemType = 0., const elemType = 0., const elemType = 0., const elemType = 0., const elemType = 0., const elemType = 0., const elemType = 0., const elemType = 0., const elemType = 0., const elemType = 0., const elemType = 0.); //不需要為Matrix提供copy constructor、destructor、 //copy assignment operator //簡化“轉換至通用型矩陣(general Matrix)”的程序 int rows() const { return 4; } int cols() const { return 4; } ostream& print(ostream&) const; void operator+=(const Matrix&); elemType operator()(int row, int column) const { return _Matrix[row][column]; } elemType& operator()(int row, int column) { return _Matrix[row][column]; } private: elemType _Matrix[4][4]; }; inline ostream& operator<<(ostream& os, const Matrix& m) { return m.print(os); } Matrix operator+(const Matrix& m1, const Matrix& m2) { Matrix result(m1); result += m2; return result; } Matrix operator*(const Matrix& m1, const Matrix& m2) { Matrix result; for (int ix = 0;ix < m1.rows();ix++) { for (int jx = 0;jx < m1.cols();jx++) { result(ix, jx) = 0; for (int kx = 0;kx < m1.cols();kx++) { result(ix, jx) += m1(ix, kx) * m2(kx, jx); } } } return result; } void Matrix::operator+=(const Matrix& m) { for (int ix = 0;ix < 4;++ix) { for (int jx = 0;jx < 4;++jx) { _Matrix[ix][jx] += m._Matrix[ix][jx]; } } } ostream& Matrix::print(ostream& os) const { int cnt = 0; for (int ix = 0;ix < 4;++ix) { for (int jx = 0;jx < 4;++jx, ++cnt) { if (cnt && !(cnt % 8)) os << endl; os << _Matrix[ix][jx] << ' '; } } os << endl; return os; } Matrix::Matrix(const elemType* array) { int array_index = 0; for (int ix = 0;ix < 4;++ix) { for (int jx = 0;jx < 4;++jx) _Matrix[ix][jx] = array[array_index++]; } } Matrix::Matrix(elemType a11, elemType a12, elemType a13, elemType a14, elemType a21, elemType a22, elemType a23, elemType a24, elemType a31, elemType a32, elemType a33, elemType a34, elemType a41, elemType a42, elemType a43, elemType a44) { _Matrix[0][0] = a11;_Matrix[0][1] = a12; _Matrix[0][2] = a13;_Matrix[0][3] = a14; _Matrix[1][0] = a21;_Matrix[1][1] = a22; _Matrix[1][2] = a23;_Matrix[1][3] = a24; _Matrix[2][0] = a31;_Matrix[2][1] = a31; _Matrix[2][2] = a33;_Matrix[2][3] = a34; _Matrix[3][0] = a41;_Matrix[3][1] = a42; _Matrix[3][2] = a43;_Matrix[3][3] = a44; } main.cpp #include "Matrix.h" int main() { Matrix m; cout << m << endl; elemType ar[16] = { 1.,0.,0.,0.,0.,1.,0.,0., 0.,0.,1.,0.,0.,0.,0.,1., }; Matrix identity(ar); cout << identity << endl; Matrix m2(identity); m = identity; cout << m2 << endl; cout << m << endl; elemType ar2[16] = { 1.3,0.4,2.6,8.2,6.2,1.7,1.3,8.3, 4.2,7.4,2.7,1.9,6.3,8.1,5.6,6.6 }; Matrix m3(ar2); cout << m3 << endl; Matrix m4 = m3 * identity; cout << m4 << endl; Matrix m5 = m3 + m4; cout << m5 << endl; m3 += m4; cout << m3 << endl; return 0; }end,
“沒有一個冬天不可逾越,沒有一個春天不會來臨,”
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/67303.html
標籤:C++
