C++面向對象程序設計雙語教程(第3版)-參考答案 劉嘉敏 【ch04】 Advance of Classes and Objects一Further Definition of Class Members and Objects_第1頁
C++面向對象程序設計雙語教程(第3版)-參考答案 劉嘉敏 【ch04】 Advance of Classes and Objects一Further Definition of Class Members and Objects_第2頁
C++面向對象程序設計雙語教程(第3版)-參考答案 劉嘉敏 【ch04】 Advance of Classes and Objects一Further Definition of Class Members and Objects_第3頁
C++面向對象程序設計雙語教程(第3版)-參考答案 劉嘉敏 【ch04】 Advance of Classes and Objects一Further Definition of Class Members and Objects_第4頁
C++面向對象程序設計雙語教程(第3版)-參考答案 劉嘉敏 【ch04】 Advance of Classes and Objects一Further Definition of Class Members and Objects_第5頁
已閱讀5頁,還剩8頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

Chapter4AdvanceofClassesandObjects-FurtherDefinitionofClassMembersandObjects1.Markthefollowingstatementsastrue(T)orfalse(F)andgivereasons.(1)Assigninganobjecttoanobjectofthesametyperesultsindefaultmember-wisecopy.(2)Memberfunctionsdeclaredconstcannotmodifytheobject.(3)Anobjectcannotbedeclaredasconst.(4)Aclasscannothaveobjectsofotherclassesasmembers.(5)Ifamemberinitializerisnotprovidedforamemberobject,thememberobject'sdefaultconstructoriscalledimplicitly.(6)Staticmembersaresharedbyallinstancesofaclass.(7)Aclass'sstaticmemberexistsonlywhenanobjectoftheclassexists.(8)TheprimaryactivityinC++iscreatingobjectsfromtheabstractdatatypesandexpressingtheinteractionsbetweenthoseobjects.(9)Aclass'sfriendfunctioncanaccessallprivatedataoftheclass.(10)Aclass'sfriendfunctionisamemberoftheclass.(1)假(F)。將對象分配給相同類型的對象不會導致默認的成員副本,它只會將指針或引用從一個對象復制到另一個對象。(2)真(T)。聲明為const的成員函數確實不能修改該對象。const成員函數被設計為不會修改對象的狀態(tài)。(3)假(F)。一個對象可以被聲明為const。當一個對象被聲明為const時,它的狀態(tài)將被視為只讀,不允許修改。假(F)。一個類可以具有其他類的對象作為成員。這被稱為對象組合,它允許一個類擁有其他類的對象作為其成員,以實現(xiàn)更復雜的行為。假(F)。如果沒有為成員對象提供成初始化設定器,會調用成員對象的默認構造函數,但這個過程是在成員對象的成員初始化列表中完成的,而不是隱式地調用。真(T)。靜態(tài)成員是屬于整個類而不是某個類的實例,因此被該類的所有實例所共享。假(F)。類的靜態(tài)成員在類的對象存在時是存在的,但即使沒有類的對象存在,靜態(tài)成員仍然存在。C++中的主要活動是建立和定義類,從而創(chuàng)建對象。通過這些對象來實現(xiàn)抽象數據類型和它們之間的交互作用。朋友函數可以訪問該類的私有數據,但不一定可以訪問所有私有數據。它只能訪問被聲明為友元的類的私有成員。朋友函數不是該類的成員函數,盡管它可以訪問該類的私有成員。朋友函數是在類外部定義的普通函數,但在類的聲明中聲明為友元函數??梢酝ㄟ^類名直接訪問。2.Findtheerror(s)ineachofthefollowingcodesandexplainpossiblecorections.略。3.Writeouttheoutputofthefollowingcodes:Ifthestatementvoidincrement(CountC,inttimes)ischangedtovoidincrement(Count&c,int×),whatwillbetheoutput?略。4.WriteaprogramthattheCubeclassisdefinedwiththepropertiesx,y,z,length,width,andheight.Theclassincludesthefollowingdefinition:(1)twoconstructors,acopyconstructorandadestructor;(2)amemberfunctiontocalculatethevolumeofCube;(3)amemberfunctiontodisplaytheproperties;(4)amemberfunctiontomoveaCube;(5)amemberfunctiontomodifythepropertiesofCube.TesttheCubeclassbyusingthemainfunction.```cpp#include<iostream>classCuboid{private:intx,y,z;intlength,width,height;public://構造函數Cuboid():x(0),y(0),z(0),length(0),width(0),height(0){}Cuboid(intx,inty,intz,intlength,intwidth,intheight):x(x),y(y),z(z),length(length),width(width),height(height){}//復制構造函數Cuboid(constCuboid&other):x(other.xy(other.y),z(other.z),length(other.length),width(other.width),height(other.height){}//析構函數~Cuboid(){}//計算魔方體積的成員函數intcalculateVolume()const{returnlength*width*height;}//顯示屬性voiddisplayProperties()const{std::cout<<\Position:(\<<x<<\\<<y<<\\<<z<<\<<std::endl;std::cout<<\Length:\<<length<<std::endl;std::cout<<\Width:\<<width<<std::endl;std::cout<<\Height:\<<height<<std::endl;}//使立方體移動的成員函數voidmove(intnewX,intnewY,intnewZ){x=newX;y=newY;z=newZ;}//修改多維數據集屬性的成員函數voidmodifyDimensions(intnewLength,intnewWidth,intnewHeight){length=newLength;width=newWidth;height=newHeight;}};intmain(){//創(chuàng)建一個魔方體對象Cuboidcuboid(1,2,3,4,5,6);//顯示屬性cuboid.displayProperties();std::cout<<\Volume:\<<cuboid.calculateVolume()<<std::endl;//移動立方體cuboid.move(7,8,9);cuboid.displayProperties();//修改屬性cuboid.modifyDimensions(10,11,12);cuboid.displayProperties();return0;}```這個程序定義了一個名為Cuboid的類,表示一個立方體。類中包含了所需的成員函數和數據成員來實現(xiàn)題目描述的功能。在主函數中,我們創(chuàng)建了一個Cuboid對象,并演示了如何使用各個成員函數來操作和顯示立方體的屬性。5.DefineaclasscalledEmployeethatcontainsaname(anobjectofthestringtype)andanemployeeID(longtype).Includeamemberfunctioncalledgetdatatogetdatafromtheuserforinsertionintotheobject,andanotherfunctioncalledputdatatodisplaythedata.Assumethenamehasnoembeddedblanks.Writeamainfunctiontoexecutethisclass.ItshouldcreateanarrayoftypeEmployee,andtheninvitetheusertoinputdataforupto100employees.Finally,itshouldprintoutthedataforalltheemployees.以下是定義一個名為`tley`的類,并包含名稱(字符串型)和雇員ID(長型)字段的代碼:```pythonclasstley:def__init__(self):=\self.employee_id=0defgetdata(self):=input(\請輸入員工的名稱:\self.employee_id=int(input(\請輸入員工的ID:\defputdata(self):print(\員工名稱:\)print(\員工ID:\self.employee_id)#主函數defmain():employees=[]n=int(input(\請輸入員工數量:\foriinrange(n):emp=tley()emp.getdata()employees.append(emp)print(\所有員工信息:\forempinemployees:emp.putdata()if__name__==\main__\main()```您可以按照以下步驟運行代碼:1.運行主函數`main()`2.輸入員數量(最多100)3.依次輸入每個員工的名稱和ID信息4.程序將打印所有員工的信息6.DefineaDictionaryclassthathastheWordobjectsdefinedintheExercisessectionofChapter3andthenumberofwords.IncludememberfunctionFindWordtofindaword,functionAddWordtoaddaword,functionGetWordtoobtainawordandfunctionPrinttooutputallwords.```cpp#include<iostream>#include<string>#include<vector>//單詞類classWord{public:Word(conststd::string&word):m_word(word){}private:std::m_word;};//字典類classDictionary{public:Dictionary():m_wordCount(0){}//查找一個單詞Word*FindWord(conststd::string&word){for(auto&w:m_words){if(w->GetWord()==word){returnw;}}returnnullptr;}//添加一個單詞voidAddWord(conststd::string&word){m_words.push_back(newWord(word));m_wordCount++;}//獲得一個單詞Word*GetWord(intindex){if(index>=0&&index<m_wordCount){returnm_words[index];}returnnullptr;}//打印輸出所有單詞voidPrintAllWords(){for(auto&w:m_words){std::cout<<w->GetWord()<<std::endl;}}private:std::vector<Word*>m_words;intm_wordCount;};intmain(){Dictionarydict;dict.AddWord(\apple\dict.AddWord(\banana\dict.AddWord(\cat\dict.PrintAllWords();return0;}```這段代碼創(chuàng)建了一個名為Dictionary的字典類,其中包含一個名為Word的對象和一個單詞的數量。在Dictionary類中,實現(xiàn)了你提到的四個成員函數:FindWord用于查找一個單詞,AddWord用于添加一個單詞,GetWord用于獲取一個單詞,PrintAllWords用于打印輸出所有單詞。7.WnitethedefinitionofthreeobjectsBank1,Bank2andBank3.Thesethreeobjectsallhaveprivatedatamemberbalanceandamemberfunctiondisplaytooutputthebalance.Designafriendfunctiontotalinthethreeobjectstocalculatethetotalbalancefromthesebanks.Testtheprograminthemainfunction.```cpp#include<iostream>classBank{private:doublebalance;public:Bank(doubleinitialBalance){balance=initialBalance;}voiddisplayBalance(){std::cout<<\余額:$\<<balance<<std::endl;}frienddoublecalculateTotalBalance(constBank&bank1,constBank&bank2,constBank&bank3);};doublecalculateTotalBalance(constBank&bank1,constBank&bank2,constBank&bank3){returnbank1.balance+bank2.balance+bank3.balance;}intmain(){Bankbank1(1000);Bankbank2(2000);Bankbank3(3000);bank1.displayBalance();bank2.displayBalance();bank3.displayBalance();doubletotalBalance=calculateTotalBalance(bank1,bank2,bank3);std::cout<<\總余額:$\<<totalBalance<<std::endl;return0;}```這個程序中定義了一個Bank類,其中私有數據成員是余額(balance)。類中有一個顯示余額的成員函數(displayBalance)。為了使calculateTotalBalance函數能夠訪問銀行對象的私有數據成員,我們在Bank類中聲明了calculateTotalBalance函數為友元函數。在主函數中,創(chuàng)建了三個銀行對象,并通過調用displayBalance函數顯示了各自的余額。然后,調用calculateTotalBalance函數計算三個銀行的總余額,并在控制臺輸出。8.DesignaclassnamedMyInteger.DrawtheUMLdiagramfortheclass.Implementtheclass.Writeatestprogramthattestsallfunctionsintheclass.Theclasscontainsthefollowing:(1)anintdatamembernamedvaluethatstorestheintvalue.(2)aconstructorthatcreatesaMfyIntegerobjectforthespecifiedintvalue.(3)aconstantgetfunctionthatreturnstheintvalue..(4)aconstantfunctionisEven(thatreturnstrueifthevalueiseven.(5)astaticfunctionisEven(int)thatreturnstrueifthespecifiedvalueiseven.(6)aconstantfunctionisEqual(constMyInteger&)thatreturnstrueifthevalueintheobjectisequaltothespecifiedobject'svalue.(7)afiunctionparseInt(conststring&)thatconvertsastringtoanintvalue.`MyInteger`類的UML關系圖:```+-------------------+|

溫馨提示

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

最新文檔

評論

0/150

提交評論