C++面向对象程序设计双语教程(第3版)-参考答案【ch04】 Advance of Classes and Objects一Further Definition of Class Members and Obje.docx

上传人:太** 文档编号:97916043 上传时间:2024-07-08 格式:DOCX 页数:13 大小:38.22KB
返回 下载 相关 举报
C++面向对象程序设计双语教程(第3版)-参考答案【ch04】 Advance of Classes and Objects一Further Definition of Class Members and Obje.docx_第1页
第1页 / 共13页
C++面向对象程序设计双语教程(第3版)-参考答案【ch04】 Advance of Classes and Objects一Further Definition of Class Members and Obje.docx_第2页
第2页 / 共13页
点击查看更多>>
资源描述

《C++面向对象程序设计双语教程(第3版)-参考答案【ch04】 Advance of Classes and Objects一Further Definition of Class Members and Obje.docx》由会员分享,可在线阅读,更多相关《C++面向对象程序设计双语教程(第3版)-参考答案【ch04】 Advance of Classes and Objects一Further Definition of Class Members and Obje.docx(13页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、Chapter4 Advance of CI asses and Objects- Further Def i ni t ion of Class Members andObjects1. Mark the fol lowing statements as true (T) or fa I se (F) and give reasons.(1) Ass igning an object to an object of the same type results i n default member-wi se copy.|7 72 3 4 5(X /( /( /(Member funct i

2、ons dec Iared const cannot mod i fy the object.An object cannot be dec Iared as const.A cI ass cannot have objects of other cI asses as members.If a member initial izer i s not prov i ded for a member object, the member objects default constructor is called imp I icitly.(6) Stat i c members are shar

3、ed by a I I i nstances of a cI ass.(7) A c I ass s stat i c member ex i sts on I y when an object of the c I ass ex i sts.(8) The pr imary activity i n C+ i s creat i ng objects from the abstract data types andexpress i ng the i nteract i ons between those ob jects.(9) A cI asss fr i end funct i on

4、can access a I I pr i vate data of the cI ass.(10) A cI ass s fr i end funct i on i s a member of the cI ass.(1)假(F)。将对象分配给相同类型的对象不会导致默认的成员副本,它只会将指针或 引用从一个对象复制到另一个对象。(2)真(T) o声明为const的成员函数确实不能修改该对象。const成员函数被设计为 不会修改对象的状态。(3)假(F) o 一个对象可以被声明为const。当一个对象被声明为const时,它的状态 将被视为只读,不允许修改。(4)假(F)o一个类可以具有其他类

5、的对象作为成员。这被称为对象组合,它允许一个 类拥有其他类的对象作为其成员,以实现更复杂的行为。(5)假(F)。如果没有为成员对象提供成初始化设定器,会调用成员对象的默认构造 函数,但这个过程是在成员对象的成员初始化列表中完成的,而不是隐式地调用。(6)真(T)o静态成员是属于整个类而不是某个类的实例,因此被该类的所有实例所 共享。(7)假(F)o类的静态成员在类的对象存在时是存在的,但即使没有类的对象存在, 静态成员仍然存在。(8) C+中的主要活动是建立和定义类,从而创建对象。通过这些对象来实现抽象数据类型和它们之间的交互作用。(9)朋友函数可以访问该类的私有数据,但不一定可以访问所有私有

6、数据。它只能访 问被声明为友元的类的私有成员。(10)朋友函数不是该类的成员函数,尽管它可以访问该类的私有成员。朋友函数是在 类外部定义的普通函数,但在类的声明中声明为友元函数。可以通过类名直接访问。int mwordCount;int main () Dictionary diet;diet. AddWord(bananadiet.AddWord(catdiet. AddWord (apple diet. PrintAllWords ();return 0;这段代码创建了一个名为Dictionary的字典类,其中包含一个名为Word的对象和一 个单词的数量。在Dictionary类中,实现了

7、你提到的四个成员函数:FindWord用于查找一 个单词,AddWord用于添加一个单词,GetWord用于获取一个单词,PrintAllWords用于打 印输出所有单词。7. Wnite the definition of three objects Bankl, Bank2 and Bank3. These three objects a I I have pr i vate data member ba Iance and a member funct i on display to output the ba Iance.Des i gn a fr i end funct i on t

8、otaI i n the three objects to caIcuI ate the totaI ba Iance from these banks. Test the program i n the ma i n funct i on.epp#include class Bank private:double balance;public:Bank(double initialBalance) balance = initialBalance;void displayBalance() std: :cout 、余额:$ balance std: :endl;)friend double

9、calculateTotalBalance(const Bankfe bankl, const Bank& bank2, const Bank& bank3);double calculateTotalBalance (const Bankfe bankl, const Bankfe bank2, const Bank& bank3) return bankl. balance + bank2. balance + bank3. balance;)int main () Bank bankl(1000);Bank bank2(2000);Bank bank3(3000);bankl.displ

10、ayBalance();bank2.displayBalance();bank3. displayBalance();double totalBalance = calculateTotalBalance(bankl, bank2, bank3);std: :cout 总余额:$ totalBalance std: :endl;return 0;这个程序中定义了一个Bank类,其中私有数据成员是余额(balance)o类中有一个显 示余额的成员函数(displayBalance)。为了使calculateTotalBalance函数能够访问银行 对象的私有数据成员,我们在Bank类中声明了 c

11、alculateTotalBalance函数为友元函数。在主函数中,创建了三个银行对象,并通过调用displayBalance函数显示了各自的余 额。然后,调用calculateTotalBalance函数计算三个银行的总余额,并在控制台输出。8. Design a c I ass named My I nteger. Draw the UML d i agram for the c I ass. Imp Iement the cI ass. Wr i te a test program that tests a I I funct i ons i n the c I ass.The cI a

12、ss conta i ns the fol lowing:(1) an i nt data member named vaIue that stores the i nt vaIue.(2) a constructor that creates a MfyInteger object for the specified va I ue.17 7 7 3 4 5 z(x Z(N z(xa constant get funct i on that returns the i nt vaIue.a constant funct i on i sEven ( that returns true i f

13、 the vaIue i s even.a static funct i on i sEven (i nt) that returns true i f the spec i f i ed ue i s even.(6) a constant funct i on i sEquaI (const My Integer&) that returns true i f the vaIue i n the ob iect i s equaI to the specif ied objects vaIue.(7) a f i unct i on parse I nt(const str i ng&)

14、that converts a str i ng to an i nt va I ue.Mylnteger类的UML关系图:、 、 、+Mylnteger+-value: int+ Mylnteger (int)| + getValue () : int |+ isEven () : bool+、 、接下来是Mylnteger类的实现:pythonclass Mylnteger:def init(self, value): self, value = valuedef getValue(self): return self, valuedef isEven(self): return self

15、, value % 2 = 0 、最后,这是一个简单的测试程序来测试Mylnteger类中的所有函数:pythondef testMylntegerClass ():# 创建一个Mylnteger对象 mylnteger = Mylnteger (10)# 测试getValue ()函数 value = mylnteger. getValue() print (Value: value) # 预期输出:10# 测试isEven()函数 isEven = mylnteger. isEven() print(Is Even: isEven) # 预期输出:True# 创建新的Mylnteger对象

16、mylnteger2 = Mylnteger (15)# 测试getValueO函数value2 = mylnteger2. getValueOprint (Value 2: value2) # 预期输出:15#测试isEvenO函数isEven2 = mylnteger2. isEvenOprint (Is Even 2: isEven2) # 预期输出:False#运行测试程序testMyIntegerClass ()2. Fi nd the error (s) in each of the fol lowing codes and exp lain possibIe corect i o

17、ns.二W呼朋. . . , . .inta;:1 . * / : . . :.三,;ptibl记:二 二匚.二二一:;、: . . . ;AA(:intx)二;,二:二:., , . . ,, . .一: . . . :2 . .、 .: . el-6;, , _ . 1” . , X . . . . . . . . , . *, :二一 . Void printO cotist :二 . . *. .- . , 二”. :;痴&b; j 二二 :;: / :一;,二二;二:痴&指向=二七三 嬴二;二 , . . , . ; cout . , . .一 , : , 1 . , . , . .

18、:. : -Dated;:.C. . _ m慧巡蚪演前筑淳滂照修泗源知熊滂滋 . . . , , . . . . . . . . . . 一. . 1 , 二::二;d为二上: * * , ,. . . . , .A :.y=o;,:二.;: . . ,.;. .二 , ,. . . . 尸.void;.:, ,. , . , . . . . . . . . . . . L . . 9. .: j coUt之之处*WMdl;.: : , , , 谜ybb.ydi;W,.,. . . . I . . . . - . . . : . . .二U ;二-y :;三 略。3. Wr ite out t

19、he output of the fol lowing codes:/classA.,.inta;::public:AO.a=0;coin constructing default A endl; A(irit x)-!;:1. , . . . . . . . , :. . . . . . . a = x; 7.:/cout constructing A endl; 1 1-AO cout destructing AK endl; class B : . .二 ,. ,:. :9. . . . . , . . . public: :.: . BO: ; :;.; . cout construc

20、ting default BM endl; . - B(int x):a(x) . coot constructing R” v endl; ,B0 cout destructing Bn cndl; . int main。 .:.一( ; ,Bbl;.Bb2(10); :;:二;:.:- :::return 0;(2)class Dumo/: ,;,:.; mtn; 二二: public: DemoO ( ,:.:Demo(mt m) n=nci: . friend Demo sqixare(Dcmo s). :Demo si; . : . . /J. , . .:sl.n5-s.n * s

21、ji; .;:.return si; 1. . . : 可;一 . .二.二C:, void dispO cout n endl; . A , .,/*void main(void)Demo a(10);a m square(a);;a.dispO; , . ./ class Demoihtn;static int sum; public: Dcmo(intx) .ec; void addO.void dispO cout、= n ,sum=w sum endl; . .mtDemosum-O; void mam() Demo a(2),b(3), c(5); a.addO; ttdispO;

22、 . . ,b.addO;b.dispO; . , . . , c.addO;c.dispO;, , - J ., J .:class Count-Y:public: , intvalue;.;,: ;J:二:二Coimt(const CountA c) value = c.value; cout *Copy an otyectn;. -CountQ ; , , , , , , ., _, ., ,. , , , . *, . . value = 0; cout Creating an object n,_,; . .f 9void increment (Count c, int time).

23、;:. . . , . * . . , com七Calling the incremeiit fiinctionnu;: ., , . , c.value+;.time+; . . . , ini mamO . *:, * . ,* Count myCourit;.int times = 0; . , - -1 . for (int i = 0; i 3; iH) . mcrementfmyCoimt, times);jeout myCount.couht is ” myCounLvaiue cndl; cout “ times is times endl;. . * . 1 , . , -,

24、 , . . ., , , , - - - - . , - - . . ,. / ./ . J J .” ,. Y .return 0;: If the statement vo i d i ncrement (Count C,i nt times) i s changed to vo i di ncrement (Count& c, i nt& times), what wi I I be the output?略。4. Wr ite a program that x, y, z, I ength, width, def i n i t i on:two constructors, a a

25、member funct i on to)z di (X)/ 7 )z 7 2 3 4 5 /( /( z( z(xthe Cube cI ass i s def i ned with the propert i esand he i ght. The cI ass i ncIudes the fol lowingcopy constructor and a destructor; caIcuI ate the voIume of Cube;a member funct i on to display the propert i es;a memberfunct i onto move a C

26、ube;a member funct i on to mod i fy the propert i es of Cube. Test the Cube cI ass by us i ng the ma i n funct i on.epp ttinclude class Cuboid private:int x, y, z;int length, width, height;public:构造函数Cuboid () : x (0), y (0), z (0), length (0), width(0), height (0) Cuboid(int x, int y, int z, int le

27、ngth, int width, int height):x (x), y (y), z (z), length (length), width (width), height (height) /复制构造函数Cuboid (const Cuboid& other):x(other.x y (other.y), z (other.z),length (other.length), width(other, width), height (other.height) /析构函数Cuboid () /计算魔方体积的成员函数 int calculateVolume() const return le

28、ngth * width * height;/显示属性void displayProperties () 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;)/使立方体移动的成员函数void move(int newX, int newY, int newZ) x = newX;y = newY;z = newZ;)/修改多维数据集属性的成员函数void modi

29、fyDimensions(int newLength, int newWidth, int newlleight) length = newLength;width = newWidth;height 二 newHeight;int main() /创建一个魔方体对象Cuboid cuboid(1, 2, 3, 4, 5, 6);/显示属性cuboid. displayProperties ();std:cout Volume: cuboid. calculateVolume() std:endl;/移动立方体cuboid. move (7, 8, 9);cuboid. displayProp

30、erties ();/修改属性cuboid. modifyDimensions (10, 11, 12);cuboid. displayProperties ();return 0;这个程序定义了一个名为Cuboid的类,表示一个立方体。类中包含了所需的成员函数 和数据成员来实现题目描述的功能。在主函数中,我们创建了一个Cuboid对象,并演示了 如何使用各个成员函数来操作和显示立方体的属性。5. Def i ne a cI ass cal led EmpIoyee that conta i ns a name (an object of the str i ng type) and an e

31、mpIoyee ID (Iong type). IncIude a member function cal led getdata to get data from the user for insertion into the object, and another function cal led putdata to display the data. Assume the name has no embedded b I anks. Wr i te a ma i n funct i on to execute th i s cI ass. 11 shouId create an arr

32、ay of type EmpIoyee, and then invite the user to i nput data for up to 100 emp I oyees. Final I y, i t shou I d pr i nt out the data for a I I the empIoyees.以下是定义一个名为tley的类,并包含名称(字符串型)和雇员ID (长型)字段的代 码:self. employee_id = 0python class tley: def _init_(self): self, name = def getdata(self):self. empl

33、oyee_id 二self, name二input (、请输入员工的名称: int (input (、请输入员工的 ID: def putdata(self):print (、员工名称: self, name)print (、员工 ID: self. employee_id)#主函数def main ():employees =n 二 int (input (请输入员工数量: for i in range(n): emp = tley ()emp. getdata()employees, append(emp)print(、所有员工信息: for emp in employees:emp. p

34、utdataOif _name_ = main_main ()您可以按照以下步骤运行代码:1 .运行主函数main。2 .输入员数量(最多100)3 .依次输入每个员工的名称和ID信息4 .程序将打印所有员工的信息6. Define a D i ct i onary cI ass that has the Word objects def i ned i n the Exerc i ses sect i on of Chapter 3 and the number of words. IncIude member function FindWord to find a word, functi

35、on AddWord to add a word, funct i on GetWord to obta i n a word and funct i on Pr i nt to output a I I words.cppttinclude ttinclude ttinclude /单词类 class Word public:Word (const std:string& word) : mword(word) private:std: m_word;);/字典类class Dictionary public:Dictionary () : m wordCount (0) )/查找一个单词W

36、ord* FindWord(const std:stringfe word) for (auto& w : m_words) if (w-GetWord() = word) return w; return nullptr;)/添加一个单词void AddWord(const std:string& word) m words, push back(new Word(word); m wordCount+;/获得一个单词Word* GetWord(int index) if (index = 0 & index m wordCount) return m_wordsindex; return nullptr;/打印输出所有单词void PrintAllWords() for (auto& w : m_words) std:cout GetWord() std:endl;)private:std:vector m_words;

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 应用文书 > 解决方案

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁