C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)-參考答案 劉嘉敏 【ch05】 Operator Overloading_第1頁
C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)-參考答案 劉嘉敏 【ch05】 Operator Overloading_第2頁
C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)-參考答案 劉嘉敏 【ch05】 Operator Overloading_第3頁
C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)-參考答案 劉嘉敏 【ch05】 Operator Overloading_第4頁
C++面向?qū)ο蟪绦蛟O(shè)計雙語教程(第3版)-參考答案 劉嘉敏 【ch05】 Operator Overloading_第5頁
已閱讀5頁,還剩7頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

Chapter5OperatorOverloading1.Markthefollowingstatermentsastrue(T)orfalse(F)andgivereasons.(1)C++allowsoperatorstobeoverloaded.(2)C++allowsnewoperatorstobecreated.(3)Anyoperatorcanbeoverloaded..(4)Howanoperatorworksonbasictypescannotbechangedbyoperatoroverloading.(5)Theassociativityofanoperatorcanbechangedbyoperatoroverloading.(6)Theprecedenceofanoperatorcannotbechangedbyoperatoroverloading.(7)Overloadedassignmentoperatorsmustbedeclaredasnon-memberfunctions.(8)Overloadedoperatormemberfunctionsforbinaryoperatorsimplicitlyusethistoobtainaccesstotheleftoperandoftheoperator.(9)Aunaryoperatorcanbeoverloadedasanon-memberfunction.(10)Abinaryoperatorcanbeoverloadedasanon-memberfunctiontakingoneargument.(11)Aconversionoperatorconvertsanobjectofoneclassintoanobjectofanotherclass.(12)The++(or-)operatorscanbeoverloadedforbothprefixandpostfixincrement(ordecrement).以下是對每個狀態(tài)的標記和理由:(1)C++允許操作符重載。--真(T)理由:C++是一種面向?qū)ο蟮木幊陶Z言,它提供了強大的操作符重載機制,允許程序員修改已有的操作符的行為。(2)C++允許創(chuàng)建新的操作符。--假(F)理由:C++不允許程序員創(chuàng)建新的操作符。操作符是由語言本身定義和實現(xiàn)的,程序員只能重載已有的操作符。(3)任何操作員都可能過載。--真(T理由:在C++中,幾乎所有的操作符都可以重載,包括算術(shù)操作符、比較操作符、邏輯操作符等。(4)操作符對基本類型的工作方式不能因操作符重載而改變。--假(F)理由:通過操作符重載,可以改操作符對基本類型的工作方式。例如,可以重載加法操作符\,使其能夠連接兩個字符串。(5)運算符的關(guān)聯(lián)性可以通過運算符重載來改變。--真(T)理由:C++允許通過操作符重載來改變運算符的關(guān)聯(lián)性。例如,可以通過重載\操作符來實現(xiàn)類似于字符串拼接的效果,將兩個字符串連接在一起。(6)假(False)。操作符的重載可以改變操作符的優(yōu)先級。例如,重載的操作符可以優(yōu)先級高于原始操作符。(7)假(False)。過載的分配操作符可以聲明為成員函數(shù)或非成員函數(shù)。通常,推薦將其聲明為成員函數(shù),以便操作符能夠訪問類的私有成員。(8)真(True)。二進制運算符的成員函數(shù)隱式地使用它來獲取對左操作數(shù)的訪問權(quán),而右操作數(shù)作為函數(shù)的參數(shù)傳遞給該函數(shù)。真(True)。一元運算符可以作為非成員函數(shù)重載,特別是當一元運算符作用于類對象時,非成員函數(shù)重載提供了更靈活的選項。(10)假(F):二進制運算符一般作為成員函數(shù)或全局函數(shù)來定義,并且通常需要兩個參數(shù)。(11)真(T):轉(zhuǎn)換運算符可以定義將一個類的對象轉(zhuǎn)換為另一個類的對象,這樣可以在類型之間進行隱式轉(zhuǎn)換。(12)真(T):前綴和后綴增量(或遞減)運算符可以被重載,使其可以根據(jù)需要在前綴或后綴位置使用。例如,++i和i++都可以使用重載的增量運算符。2.Giventhefollowingprogram.Defineoverloadingoperators=,+and++andwriteouttheoutputoftheprogram.略。3.WriteaprogramthatdefinesaDateclasstoimplementthefollowingoperations:(1)Printadate;(2)Incrementthedatebyonemonth;(3)Comparetwodatesbyrelationoperators=,<=,and!=;(4)Overloadinsertion(>>)andextraction(<<)operatorsforeasyinputandoutput.(TheDateclassrequirestheusertoinput/outputadateintheform:dd/mm/yy)```cpp#include<iostream>#include<sstream>classDate{private:intday;intmonth;intyear;public:Date(intd,intm,inty):day(d),month(m),year(y){}voidprintDate(){std::cout<<day<<\<<month<<\<<year<<std::endl;}voidaddOneMonth(){month++;if(month>12){month=1;year++;}}booloperator==(constDate&other)const{return(day==other.day&&month==other.month&&year==other.year);}booloperator<=(constDate&other)const{return(year<other.year||(year==other.year&&month<other.month)||(year==other.year&&month==other.month&&day<=other.day));}booloperator!=(constDate&other)const{return!(*this==other);}friendstd::istream&operator>>(std::istream&is,Date&date){std::stringinput;std::getline(is,input);std::stringstreamss(input);std::stringtoken;std::getline(ss,token,'/');date.day=std::stoi(token);std::getline(ss,token,'/');date.month=std::stoi(token);std::getline(ss,token);date.year=std::stoi(token);returnis;}friendstd::ostream&operator<<(std::ostream&os,constDate&date){os<<date.day<<\<<date.month<<\<<date.year;returnos;}};intmain(){Datedate(1,1,2022);date.printDate();date.addOneMonth();date.printDate();DateanotherDate(31,12,2021);if(date==anotherDate){std::cout<<\Datesareequal.\<<std::endl;}elseif(date<=anotherDate){std::cout<<\Dateislessthanorequaltoanotherdate.\<<std::endl;}else{std::cout<<\Dateisgreaterthananotherdate.\<<std::endl;}std::cout<<\Enteradate(dd/mm/yy):\std::cin>>date;std::cout<<\EnteredDate:\<<date<<std::endl;return0;}```這個程序創(chuàng)建了一個名為Date的類,用于處理日期。它具有打印日期、增加一個月、比較兩個日期和輸入/輸出日期的功能。在主函數(shù)中,我們創(chuàng)建一個Date對象并使用printDate方法打印日期。然后,我們使用addOneMonth方法將日期增加一個月,并再次打印日期。接下來,我們創(chuàng)建另一個Date對象,并使用關(guān)系運算符來比較兩個日期。最后,我們使用重載的輸入和輸出操作符來輸入和輸出日期。請注意,此程序假設(shè)用戶輸入的日期格式符合\dd/mm/yy\的要求,比較操作符(==、<=和!=)和輸入/輸出操作符(<<和>>)都被重載為類的成員方法或友元函數(shù)。4.Giventhefollowingprogram:WriteoutthedefinitionsofallmemberfunctionsandafriendfunctionwithintheCVectorclassandtesttheminthemainfunction.略。5.GiventhedeclarationoftheIntegerclass:(1)WritethedefinitionofallmemberfunctionsoutsidetheIntegerclass.(2)Writethemainfunctiontotestthem.略。6.DefinetheCounterclassincludingoverloadingoperator++.下面是一個示例的計數(shù)器類,包括重載了前置和后置自增運算符(++)的實現(xiàn):```pythonclassCounter:def__init__(self,count=0):self.count=countdef__repr__(self):returnf\Counter(count={self.count})\defincrement(self):self.count+=1def__iadd__(self,other):ifisinstance(other,int):self.count+=otherelse:raiseTypeError(\Countercanonlybeincrementedbyaninteger.\returnselfdef__add__(self,other):ifisinstance(other,int):returnCounter(self.count+other)else:raiseTypeError(\Countercanonlybeaddedtoaninteger.\def__radd__(self,other):returnself.__add__(other)def__pos__(self):self.increment()returnselfdef__rshift__(self,other):ifisinstance(other,int):self.count=otherelse:raiseTypeError(\Countercanonlybeassignedanintegervalue.\returnself.countdef__rrshift__(self,other):returnself.__rshift__(other)#實例化計數(shù)器對象c1=Counter(5)print(c1)#Output:Counter(count=5)#前置自增運算符(++)++c1print(c1)#Output:Counter(count=6)#后置自增運算符(++)c1++print(c1)#Output:Counter(count=7)#操作符重載:+=c1+=3print(c1)#Output:Counter(count=10)#操作符重載:+c2=c1+5print(c2)#Output:Counter(count=15)#操作符重載:+=c2+=c1print(c2)#Output:Counter(count=25)#操作符重載:+c3=20+c2print(c3)#Output:Counter(count=45)#操作符重載:+++c3print(c3)#Output:Counter(count=46)#操作符重載:>>c3>>100print(c3)#Output:Counter(count=100)#操作符重載:>>=c3>>=50print(c3)#Output:50```7.WhentheC++programisrunning,itwillnotcheckwhetheranarrayisoutofboundautomatically.WriteaprogramthatcandoitbyoverloadingoperatorD.當C++程序運行時,它并不會自動檢查數(shù)組是否越界。然而,你可以編寫一個程序來通過重載操作符D來實現(xiàn)對數(shù)組的越界檢查。下面是一個簡單的示例程序:```cpp#include<iostream>classArray{private:int*data;intsize;public:Array(intn){size=n;data=newint[size];}~Array(){delete[]data;}int&operator[](intindex){if(index<0||index>=size){std::cout<<\Error:Arrayindexoutofbounds\<<std::endl;exit(1);}returndata[index];}};intmain(){Arrayarr(5);//設(shè)置元素值arr[0]=1;arr[1]=2;arr[2]=3;arr[3]=4;arr[4]=5;//訪問數(shù)組元素for(inti=0;i<6;i++){std::cout<<\arr[\<<i<<\=\<<arr[i]<<std::endl;}return0;}```在這個例子中,我們創(chuàng)建了一個名為Array的類,它封裝了一個動態(tài)分配的整型數(shù)組。通過重載操作符[],我們可以使用像`arr[i]`這樣的語法來訪問數(shù)組元素。在重載的操作符函數(shù)中,我們首先檢查索引是否越界,如果越界,我們輸出錯誤信息并終止程序。如果索引沒有越界,則返回對應的數(shù)組元素的引用。在主函數(shù)中,我們創(chuàng)建了一個大小為5的Array對象,并設(shè)置了一些元素的值。然后,我們使用一個循環(huán)嘗試訪問6個元素,其中最后一個是越界的。當程序嘗試訪問越界的元素時,它會顯示錯誤信息并退出。8.ModifytheTimeDemoclasstoimplementtheinputandoutputofthetime.Overloadingoperator>>toinputtimefromtheuser.Overloadingoperator<<tooutputthetimetoconsole.```pythonclassTime:def__init__(self,hour=0,minute=0,second=0):self.hour=hourself.minute=minuteself.second=second#重載>>操作符用于從用戶輸入時間def__rshift__(self,other):time_str=input(\請輸入時間(格式:hh:mm:ss):\time_list=time_str.split(\\self.hour=int(time_list[0])self.minute=int(time_list[1])self.second=int(time_list[2])#重載<<操作符用于輸出時間到控制臺def__lshift__(self,other):print(f\現(xiàn)在的時間是:{self.hour:02d}:{self.minute:02d}:{self.second:02d}\```使用這個修改后的類,你可以這樣輸入和輸出時間:```pythontime=Time()time>>None#輸入時間time<<None#輸出時間```這個類中,我們使用了`__rshift__`方法重載了`>>`操作符,以實現(xiàn)從用戶輸入時間。然后使用`__lshift__`方法重載了`<<`操作符,以實現(xiàn)將時間輸出到控制臺。9.DesignaPercentclassthatrepresentsthepercentageof10%,80%andetc.Overloadoperators<<and>>toimplementtheoutputandinputofPercentobjects;Overloadoperators==and<tocomparetherelationshipoftwoPercentobjects.```cpp#include<iostream>classPercentage{public:Percentage(intvalue):m_value(value){}friendstd::ostream&operator<<(std::ostream&os,constPercentage&percentage);friendstd::istream&operator>>(std::istream&is,Percentage&percentage);friendbooloperator==(constPercentage&p1,constPercentage&p2);friendbooloperator<(constPercentage

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論