




已閱讀5頁,還剩20頁未讀, 繼續(xù)免費閱讀
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
第十四章 重載操作符與轉(zhuǎn)換1。在什么情況下重載操作符與內(nèi)置操作符不同?在什么情況下重載操作符與內(nèi)置操作符相同?重載操作符必須具有至少一個類類型或枚舉類型的操作數(shù)。重載操作符不保證操作數(shù)的求值順序,例如對 & 和 | 的重載版本不再具有“短路求值”的特性,兩個操作數(shù)都要進(jìn)行求值,而且不規(guī)定操作數(shù)的求值順序。對于優(yōu)先級和結(jié)合性及操作數(shù)的數(shù)目都不變。2。為Sales_item編寫輸入、輸出。加以及復(fù)合賦值操作符的重載聲明。class Sales_item friend std:istream& operator ( std:istream&, Sales_item& );friend std:ostream& operator (std:ostream&, const Sales_item&);public:Sales_item& operator += ( const Sales_item& );Sales_item operator+ ( const Sales_item&, const Sales_item& )3。解釋如下程序,假定Sales_item構(gòu)造函數(shù)的參數(shù)是一個string,且不為explicit.解釋如果構(gòu)造函數(shù)為explicit會怎樣。string null_book = “0-000-00000-0”;Sales_item item(cin);item += null_book;第一句:調(diào)用接受一個C風(fēng)格的字符串形參的string構(gòu)造函數(shù),創(chuàng)建一個string臨時對象,然后使用string復(fù)制構(gòu)造函數(shù)用這個臨時對象初始化string對象null_book,第二句:從標(biāo)準(zhǔn)輸入設(shè)備讀入數(shù)據(jù),創(chuàng)建Sales_item對象item。第三句:首先調(diào)用接受一個string參數(shù)的Sales_item構(gòu)造函數(shù),創(chuàng)建一個臨時對象,然后調(diào)用Sales_item的復(fù)合重載操作符+=,將這個Sales_item臨時對象加到item對象上,如果構(gòu)造函數(shù)為explicit,則不能進(jìn)行從string對象到Sales_item對象的隱式轉(zhuǎn)換,第三句將不能被編譯。4。string和vector類都定義了一個重載的=,可用于比較這些類的對象,指出下面的表達(dá)式中應(yīng)用了哪個=版本。string s; vector svec1, svec2;“cobble” = “store” 應(yīng)用了C+語言內(nèi)置版本的重載=svec10 = svec20; 應(yīng)用了string版本的重載=svec1 = svec2 應(yīng)用了vector版本的重載=5。列出必須定義為類成員的操作符。賦值 = , 下標(biāo) , 調(diào)用 () ,成員訪問箭頭 - 6。解釋下面操作符是否應(yīng)該為類成員,為什么?(a)+ (b) += (c)+ (d) - (e) (f) & (g) = (h) ( )+, 和()必須定義為成員,否則會出現(xiàn)編譯錯誤;+= 和 + 會改變對象的狀態(tài),通常會定義為類成員。7。為下面的ChecoutRecord類定義一個輸出操作符:class CheckoutRecordpublic:/ .private:double book_id;string title;Date date_borrowed;Date date_due;pair borrower;vector pair* wait_list;ostream&operator (ostream& out, const CheckoutRecord& s) out s.book_id t s.title t s.date_borrowed t s.date_due t ; out borrower: s.borrower.first , s.borrower.second endl; out wait_list: endl; for ( vector pair* :const_iterator it = s.wait_list.begin();it != s.wait_list.end(); +it ) out t first , second endl; return out;8。在12.4節(jié)的習(xí)題中,你編寫了下面某個類的框架: (b) Date為所選擇的類編寫輸出操作符。#includeusing namespace std;class Datepublic:Date() Date( int y, int m, int d )year = y; month = m; day = d;friend ostream& operator ( ostream&, const Date& );private:int year, month, day;ostream& operator ( ostream& out, const Date& d )out year: d.year t month: d.month t day: d.day endl;int main() Date dt(1988, 12, 01); cout dt ( istream& in, Sales_item& s )double price;in s.isbn s.units_sold price;s.revenue = s.units_sold * price;return in;如果將習(xí)題14.9中的數(shù)據(jù)作為輸入,將會發(fā)生什么?上述的輸入操作符中 缺少了對錯誤輸入情況的判斷與處理,會導(dǎo)致錯誤的情況發(fā)生。(a)的輸入沒有問題,但是(b)的輸入,將形參Sales_item對象的ISBN成員值為10, units_sold和revenue成員保持原值不變。11。為14.2.1節(jié)習(xí)題中定義的CheckoutRecord類定義一個輸入操作符,確保該類操作符處理輸入錯誤。class CheckoutRecordpublic:/ friend istream& operator( istream&, CheckoutRecord& ); / 聲明為類的友元/ ;istream & operator ( istream& in, CheckoutRecord& c ) cout c.book_id c.title;/ Input Data data_borrowed and data_duecout c.date_borrowed; /.year c.date_borrowed.month c.date_borrowed.day;/ Input Data data_due and data_duecout c.date_due;/.year c.date_due.month c.date_due.day;/ Input the pair borrowercout Input the pair borrower (string) :n;in c.borrower.first c.borrower.second;if ( !in )c = CheckoutRecord(); return in;/ Input wait_listcout Input the wait_list (string) :n;c.wait_list.clear();while ( in )pair *ppr = new pair;in ppr-first ppr-second;if ( !in )delete ppr;return in;c.wait_list.push_back( ppr ); return in;輸入錯誤的情況:輸入正確的情況:12。編寫Sales_item操作符,用+進(jìn)行實際加法,而+=調(diào)用+。與本節(jié)中操作符的實現(xiàn)方法相比較,討論這個方法的缺點。Sales_item Sales_item:operator+( const Sales_item& rhs )units_sold += rhs.units_sold;revenue += rhs.revenue;return *this;將下面定義的非成員+=操作符聲明為類Sales_item的友元:Sales_item operator+=( Sales_item& lhs, const Sales_item& rhs )lhs = lhs + rhs;return lhs;這個方法缺點:在+=操作中需要創(chuàng)建和撤銷一個臨時Sales_item對象,來保存+操作的結(jié)果,沒有本節(jié)中的方法簡單有效。13。如果有,你認(rèn)為Sales_item還應(yīng)該有哪些其他的算術(shù)操作符?定義你認(rèn)為的該類應(yīng)包含的那些。還應(yīng)有-操作符,定義為類的非成員,相應(yīng)地還應(yīng)該有 -= 復(fù)合操作符并定義為類的成員。Sales_item& Sales_item:operator-=( const Salse_item& rhs )units_sold -= rhs.units_sold;revenue -= rhs.revenue;return *this;Sales_item operator-( const Sales_item &lhs, const Sales_item & rhs )Sales_item ret(lhs);ret -= rhs;return ret;14。定義一個賦值操作符,將isbn賦值給Sales_item對象。Sales_item& Sales_item:operator=( const string & s )sbn = s;return *this;10。為14.2.1節(jié)習(xí)題中介紹的CheckoutRecord類定義賦值操作符。主函數(shù)中定義了兩個 CheckoutRecord 類的對象,調(diào)用了CheckoutRecord 類的 =賦值操作符,效果如下截圖:int _tmain(int argc, _TCHAR* argv)CheckoutRecord c1;cin c1;CheckoutRecord c2;c2 = c1; / 調(diào)用了類的賦值操作符=std:cout c2 std:endl; / 輸出對象c2的內(nèi)容system(pause);return 0;/ CheckoutRecord類中賦值操作符定義為:/ 重載操作符=CheckoutRecord& CheckoutRecord:operator =( const CheckoutRecord& cr )book_id = cr.book_id;title = cr.title;date_borrowed = cr.date_borrowed; / 前提:必須在Date類里也重載操作符=date_due = cr.date_due; / as before/ 對pair進(jìn)行賦值操作borrower.first = cr.borrower.first;borrower.second = cr.borrower.second;/ 對vector進(jìn)行賦值操作wait_list.clear(); / 首先清空for ( vector pair* :const_iterator it = cr.wait_list.begin();it != cr.wait_list.end(); + it )pair *ppr = new pair;ppr-first = (*it)-first;ppr-second = (*it)-second;wait_list.push_back( ppr );return *this;16。CheckoutRecord類還應(yīng)該定義其他賦值操作符嗎?如果是,解釋哪些類型應(yīng)該用作操作數(shù)并解釋為什么。為這些類型實現(xiàn)賦值操作符。從應(yīng)用角度考慮,可能會修改預(yù)約時間date_due,可通過設(shè)置新的賦值操作符來實現(xiàn);或者是往wait_list里添加排隊讀者,也可以通過設(shè)置新的賦值操作符來實現(xiàn)。/ set new date_dueCheckoutRecord& CheckoutRecord:operator=( const& new_due )date_due = new_due;return *this;/ add new readers who wait for some booksCheckoutRecord& CheckoutRecord:operator=( const std:pair& new_waiter )pair *ppr = new pair;*ppr = new_waiter;wait_list.push_back( ppr );return *this;17。14.2.1節(jié)習(xí)題中定義了一個CheckoutRecord類,為該類定義一個下標(biāo)操作符,從等待列表中返回一個名字。下標(biāo)重載:pair& CheckoutRecord:operator ( const vector pair* :size_type index )return *wait_list.at( index ); / 下標(biāo)操作符重載const pair& CheckoutRecord:operator ( const vector pair* :size_type index ) constreturn *wait_list.at( index );18。討論用下標(biāo)操作符實現(xiàn)這個操作的優(yōu)缺點。優(yōu)點:使用簡單。缺點:操作的語義不夠清楚,因為CheckoutRecord不是一個通常意義上的容器,而且等待者也不是CheckoutRecord容器中的一個元素,不易使人弄明白怎樣用。19。提出另一種方法定義這個操作。可以將這個操作定義成普通的函數(shù), pair& get_a_waiter( const size_t index ) 和 const pair& get_a_waiter ( const size_t index ) const.20。在ScreenPtr類的概略定義中,聲明但沒有定義賦值操作符,請實現(xiàn)ScreenPtr賦值操作符。ScreenPtr& operator=( const ScreenPtr& sp )+sp.ptr-use;if ( -ptr-use = 0 )delete ptr;ptr = sp.ptr;return *this;21。定義一個類,該類保存一個指向ScreenPtr的指針。為該類定義一個重載的箭頭操作符。class NoNamepublic:NoName( *p ): ps( new ScreenPtr(p) ) ScreenPtr operator-( )return *ps;const ScreenPtr operator-( ) constreturn *ps;NoName()delete ps;private:ScreenPtr *ps;22。智能指針可能應(yīng)該定義相等操作符和不等操作符,以便測試兩個指針是否相等或不等。將這些操作加入到ScreenPtr類。class ScreenPtrpublic:/ friend inline bool operator=( const ScreenPtr &, const ScreenPtr &); friend inline bool operator!=( const ScreenPtr &, const ScreenPtr &);private:ScrPtr *ptr;/ operator =inline bool operator=( const ScreenPtr &p1, const ScreenPtr &p2 )return p1.ptr = p2.ptr;/ operator !=inline bool operator!=( const ScreenPtr &p1, const ScreenPtr &p2 )return !( p1.ptr = p2-.ptr );23。CheckedPtr 類表示指向數(shù)組的指針。為該類重載下標(biāo)操作符和解引用操作符。使操作符確保CheckedPtr有效:它應(yīng)該不可能對超出數(shù)組末端的元素進(jìn)行解引用或索引。/ 下標(biāo)操作符重載int& CheckedPtr:operator( const size_t index )if ( beg + index = end )throw out_ot_range( “ invalid index“ );return *( beg + index );const int & CheckedPtr:operator ( const size_t index ) constif ( beg + index = end )throw out_ot_range( “ invalid index“ );return *( beg + index );/ 解引用操作符重載int CheckedPtr:operator*()if ( curr = end )throw out_of_range( “ invalid current pointer” );return *curr;const int& CheckedPtr:operator*() constif ( curr = end )throw out_of_range(“ invalid current pointer”);return *curr;24。習(xí)題14.23中定義的解引用操作符或下標(biāo)操作符,是否也應(yīng)該檢查對數(shù)組起點之前的元素進(jìn)行的解引用或索引?解釋你的答案。對于下標(biāo)操作符,應(yīng)該進(jìn)行檢查,因為當(dāng)用戶給出的下標(biāo)索引值小于0時,編譯器不會出現(xiàn)編譯錯誤,而會出現(xiàn)運行時錯誤。應(yīng)修改為:/ 下標(biāo)操作符重載int& CheckedPtr:operator( const size_t index )if ( beg + index = end | beg + index = end | beg + index beg )throw out_ot_range( “ invalid index“ );return *( beg + index );而對于解引用操作符,返回curr所指向的數(shù)組元素,在創(chuàng)建對象時已經(jīng)將curr初始化為指向數(shù)組的第一個元素,只有當(dāng)執(zhí)行操作時才會對curr進(jìn)行減的操作,而操作符已經(jīng)對curr的值與數(shù)組起點進(jìn)行了檢查,所以不用再在這里檢查。25。為了表現(xiàn)得像數(shù)組指針,CheckedPtr類應(yīng)實現(xiàn)相等和關(guān)系操作符,以便確定兩個CheckedPtr對象是否相等,或者一個小于另一個,諸如此類。為CheckedPtr類增加這些操作。應(yīng)將這些操作符聲明為CheckedPtr的友元。/ 相等操作符bool operator=( const CheckedPtr& lhs, const CheckedPtr& rhs )return lhs.beg = rhs.beg & lhs.end = rhs.end & lhs.curr = rhs.curr;bool operator!=( const CheckedPtr & lhs, const CheckedPtr& rhs )return !( lhs = rhs );/ 關(guān)系操作符bool operator( const CheckedPtr & lhs, const CheckedPtr& rhs )return lhs.beg = rhs.beg & lhs.end = rhs.end & lhs.curr ( const CheckedPtr & lhs, const CheckedPtr& rhs )return lhs.beg = rhs.beg & lhs.end = rhs.end & lhs.curr rhs.curr;bool operator rhs.curr );bool operator =( const CheckedPtr & lhs, const CheckedPtr& rhs )return !( lhs.curr temp.end )throw out_of_range(“ Too large n, over.”);return temp;CheckedPtr operator-( const CheckedPtr& lhs, const size_t n )CheckedPtr temp( lhs );temp.curr -= n;if ( temp.curr temp.beg )throw out_of_range(“ Too large n, over.”);return temp;用到了復(fù)制構(gòu)造函數(shù),定義為:CheckedPtr:CheckedPtr( const CheckedPtr& cp ):beg( cp.beg ), end( cp.end ), curr( cp.curr ) 27。討論允許將空數(shù)組實參傳給CheckedPtr構(gòu)造函數(shù)的優(yōu)缺點。優(yōu)點:構(gòu)造函數(shù)的定義簡單。缺點:導(dǎo)致構(gòu)造的對象沒有指向有效的數(shù)組,從而失去使用價值。應(yīng)該在構(gòu)造函數(shù)里控制參數(shù)確保beg();const Screen* operator-() const;/ 解引用操作Screen& operator*();const Screen& operator*();private:Screen *beg;Screen *end;Screen *curr;CheckPtr& CheckPtr:operator+()if ( curr = end )throw out_of_range( “increment past the end of CheckedPtr”);+curr;return *this;CheckPtr& CheckPtr:operator()if ( curr = begin )throw out_of_range( “decrement past the beginning of CheckedPtr”);-curr;return *this;/ 后綴式CheckPtr& CheckPtr:operator+( int )CheckedPtr temp( *this );+*this;return temp;CheckPtr& CheckPtr:operator( int )CheckedPtr temp( *this );-*this;return temp;/ 箭頭操作符Screen* CheckedPtr:operator-()return curr;const Screen* CheckedPtr:operator-() constreturn curr;Screen& CheckedPtr:operator*()if ( curr = end )throw out_of_range( “invalid current pointer.”);return *curr;const Screen& CheckedPtr:operator*() constif ( curr = end )throw out_of_range( “invalid current pointer.”);return *curr;31。定義一個函數(shù)對象執(zhí)行“如果則否則”操作;該函數(shù)對象應(yīng)接受三個形參;它應(yīng)該測試第一個形參;如果測試成功,則返回第二個形參;否則,返回第三個形參。class NoNamepublic:NoName() NoName( int i1, int i2, int i3 ): iVal1( i1 ), iVal2( i2 ), iVal3( i3) int operator() ( int i1, int i2, int i3 )return i1? i2: i3;private:int iVal1;int iVal2;int iVal3;32。一個重載的函數(shù)調(diào)用操作符可以接受多少個操作數(shù)?0個或多個。33。使用標(biāo)準(zhǔn)庫算法和GT_cls類,編寫一個程序查找序列中第一個比指定值大的元素。/ 14.33_Gt_cls_and_algorithm.cpp : 定義控制臺應(yīng)用程序的入口點。/#include stdafx.h#include #include #include #include using namespace std;class GT_clspublic:GT_cls( const string gW = ) : givenWord( gW ) bool operator() ( const string &s )return ( s givenWord );private:std:string givenWord;int _tmain(int argc, _TCHAR* argv)std:cout Input some words( ctrl + z to end ): std:endl;vector text;string word;while ( std:cin word )text.push_back( word ); / end of inputthe text/ input the given wordstd:cin.clear();std:cout gWord;/deal with text , to realize find the first word which is bigger than the given wordvector:iterator it = find_if( text.begin(), text.end(), GT_cls( gWord );if ( it != text.end() )std:cout n Then the first word in the text you input, std:endl twhich is bigger than the given word is: std:endl t *it std:endl;system(pause);return 0; 34。編寫類似于GT_cls的類,但測試兩個值是否相等。使用該對象和標(biāo)準(zhǔn)庫算法編寫程序,替換序列中給定值的所有實例。/ 14.34_GT_cls.cpp : 定義控制臺應(yīng)用程序的入口點。#include stdafx.h#include #include #include #include using namespace std;class GT_clspublic:GT_cls( int iVal = 0 ) : val( iVal ) bool operator() ( const int & iv )return ( iv = val );private:int val;int _tmain(int argc, _TCHAR* argv)std:cout Input some nums( ctrl + z to end ): std:endl;vector iVec;int iVal;while ( std:cin iVal)iVec.push_back( iVal ); / end of inputthe iVeccin.clear();cout rp;cout givenNum;/ replacereplace_if( iVec.begin(), iVec.end(), GT_cls( rp ), givenNum );cout Now , the new vector iVec, is : nt;for ( vector:iterator it = iVec.begin(); it != iVec.end(); +it )cout *it ;system(pause);return 0;35。編寫類似于GT_cls的類,但測試給定string對象的長度是否與其邊界相匹配。報告輸入中有多少單詞的長度在1到10之間。/ 14.35_BT_cls.cpp : 定義控制臺應(yīng)用程序的入口點。/#include stdafx.h#include #include #include #include using namespace std;class BT_clspublic:BT_cls( size_t len1 = 0, size_t len2 = 0 ) if ( len1 = minlen & s.size() = maxlen );private:std:string:size_type minlen, maxlen;bool isShorter( const string &s1, const string &s2 ) return s1.size() s2.size();int _tmain(int argc, _TCHAR* argv)std:cout Input some words( ctrl + z to end ): std:endl;vector text;string word;while ( std:cin word )text.push_back( word ); / end of inputthe text/deal with textsort( text.begin(), text.end() );text.erase( unique( text.begin(), text.end() ), text.end() );stable_sort( text.begin(), text.end(), isShorter );/ to count how many words length are between 1-10vector:size_type cnt = count_if( text.begin(), text.end(), BT_cls( 1, 10 );std:cout There are cnt words length is between 1-10. std:endl;system(pause);return 0;36。修改前一段程序以報告在1到9之間以及10以上的單詞的數(shù)目。/ 14.36_BT_cls_Words.cpp : 定義控制臺應(yīng)用程序的入口點。/#include stdafx.h#include #include #include #include using namespace std;class BT_clspublic:BT_cls( size_t len1 = 0, size_t len2 = 0 ) : minlen( len1 ), maxlen( len2 ) bool operator() ( const string &s )return ( s.size() = minlen & s.size() = maxlen );private:std:string:size_type minlen, maxlen;int _tmain(int argc, _TCHAR* argv)std:cout Input some words( ctrl + z to end ): std:endl;vector text;string word;while ( std:cin word )text.push_back( word ); / end of inputthe textstd:cin.clear();/deal with text , to count how many words length are between 1-9size_t cnt = count_if( text.b
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- (期末培優(yōu)卷)期末高頻易錯培優(yōu)卷(含答案解析)八年級下冊英語
- 記賬實操-污水處理企業(yè)賬務(wù)處理的示例
- 人工智能機(jī)器人教育與培訓(xùn)行業(yè)深度調(diào)研及發(fā)展項目商業(yè)計劃書
- 人生禮儀舞蹈保護(hù)AI應(yīng)用行業(yè)跨境出海項目商業(yè)計劃書
- 跨界合作零售體驗店企業(yè)制定與實施新質(zhì)生產(chǎn)力項目商業(yè)計劃書
- 人工智能音樂治療行業(yè)深度調(diào)研及發(fā)展項目商業(yè)計劃書
- 會員等級制度與權(quán)益升級創(chuàng)新創(chuàng)業(yè)項目商業(yè)計劃書
- “象外之意”導(dǎo)引兒童的水墨畫教學(xué)
- 2024-2025版高中地理第4章工業(yè)地域的形成與發(fā)展學(xué)科素養(yǎng)學(xué)案新人教版必修2
- 《餐飲服務(wù)與管理綜合實訓(xùn)(第3版)》教案-餐飲點菜單的設(shè)計教案
- 科學(xué)二年級第二學(xué)期雙減期末綜合測評方案
- 關(guān)于涉農(nóng)企業(yè)稅收風(fēng)險管理的實踐和思考
- 6.醫(yī)院感染綜合性監(jiān)測制度
- 05S502閥門井圖集
- 定語從句語法講解
- 畢業(yè)設(shè)計英文文獻(xiàn)中文翻譯_TCP分離器_基于可重構(gòu)硬件的TCPIP流量監(jiān)控
- 輪扣式支架模板施工方案
- 貨物及服務(wù)招標(biāo)和外貿(mào)代理服務(wù)商資格遴選項目遴選文件.docx
- 雙門通道控制(共20頁)
- 圖像的頻域增強(qiáng)
- 法蘭標(biāo)準(zhǔn)(excel版本)化工部HG20592-2009
評論
0/150
提交評論