




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
1、mi Viewing Hints Book Home Page Free Newsletter Seminars Seminars on CD ROM Consulting Annotated Solution GuideRevision 1.0for Thinking in C+, 2nd edition, Volume 1by Chuck Allison? 2001 Min dView, I nc. All Rights Reserved.Previous Chapter Table of Contents Next Chapter Cha pter 44-1In the Stan dar
2、d C library, the function pu ts( ) prints a char array to the con sole (so you can say puts(hello). Write a C program that uses puts( )but does not include or otherwise declare the fun cti on. Comp ile this p rogram with your C comp iler. (Some C+ comp ilers are not disti net from their C comp ilers
3、; in this case you may n eed to discover a comma nd-li ne flag that forces a C comp ilati on.) Now comp ile it with the C+ comp iler and note the differe nee.(Left to the reader)4-2Create a struct declarati on with a si ngle member function, the n create a defi niti on for that member fun cti on. Cr
4、eate an object of your new data type, and call the member function.(see the n ext exercise)“guarded ” header file,4-3Change your solution to Exercise 2 so the struct is declared in a properlywith the definition in one cpp file and your main( ) in another.Solutio n::S04:MyStruct.h#ifndef MY STRUCT H
5、#defi ne MY STRUCT H struct MyStruct void f();#e ndif /: /: S04:MyStruct.c pp 0 #in clude MyStruct.h #in clude using n ames pacestd;void MyStruct:f() cout MyStruct:fn; /: /: S04:Exercise3.c pp /L MyStruct #in clude MyStruct.hint mai n() MyStruct m;/:The #ifndef statement in MyStruct.h guarantees tha
6、t the file will not be included more than oncein any compilation, which isn t an issue here, but in large projects ites s not unusual for heato be logically in cluded mult iple times. The defi ned prepro cessor op erator p rovides an alter natemeans of check ing for defi ned prepro cessor symbols, a
7、s follows:#if !defi ned(M YSTRUCT_H)This form allows multiple conditions to be tested with logical connectives such as|and & .4-4Create a struct with a single int data member, and two global functions, each of which takes a pointer to that struct. The first function has a second int argument and set
8、s the struct int to the argume nt value, the sec ond dis plays the int from the struct. Test the functions.(see the n ext exercise.)4-5Rep eat Exercise 4 but move the functions so they are member functions of the struct, and test agai n.Solutio n:/: S04:GetSet.c pp #in clude using n ames pacestd;str
9、uct Hasint int x;void set In t(i nt n ewX) x = n ewX;int get lnt() return x;int mai n() HasI nt h;h.set In t(5);cout h.get In t() en dl; / 5/:It is very com mon for a class to have such get- and set-members like this one does. In this exa mple I could have sep arated the class defi niti on and the m
10、ember function impi eme ntati on like I did in exercise nu mber 3 above, but I did n t for two reasons: 1) I m lazy, and 2) I wan ted toremind you that when you define member function bodies in situ like this (i.e., inside the classdefi niti on), they are imp licitly inline fun ctio ns.4-6 Create a
11、class that (redu ndan tly) p erforms data member select ion and a member function call using the this keyword (which refers to the address of the curre nt object).Solutio n:/: S04:UsesThis.c pp #in elude using n ames pacestd;struct Hasint int x;void setI nt(i nt x) this-x = x;int get lnt() return th
12、is-x;void dis playO cout getI nt() en dl;int mai n() HasI nt h;h.set In t(5);h.dis play(); / 5/:This is a variation on the previous exercise. The use of this is actually necessary in Haslnt:setlnt to disambiguate the p arameter x from the member x.4-7Make a Stash that holds doubles. Fill it with 25
13、double values, the n print them out to the con sole.(Left to the reader)4-8Rep eat Exercise 7 with Stack.(Left to the reader)4-9Create a file containing a function f( ) that takes an int argume nt and prints it to the con sole using the printf( ) function in by saying: printf( “ dl , i)n which i is
14、the int you wish to print. Create a separate file containing main( ), and in this file declare f( ) to take a float argument. Call f( ) from in side main( ). Try to comp ile and link your p rogram with the C+ comp iler and see what happens. Now comp ile and link the p rogram using the C comp iler, a
15、nd see what happens whe n it runs. Explain the behavior.Solutio n:This exercise illustrates typ e-safe lin kage. In C+ function n ame are decorated (aka man gled) to in clude in formati on about their argume nts. The con seque nee is that the n ame the lin ker sees is actually quite different than w
16、hat you see. For example, f(int) might appear to the linker as f_F1i (a function taking one int), say, and f(double) as f_F1d. Since the names are distinet, you get a linker error. In C the names are the same, allowing you to call f(double) with an int, which is an error.4-10Find out how to p roduce
17、 assembly Ian guage from your C and C+ com pilers. Write a fun ctio n in C and a struct with a si ngle member fun cti on in C+. P roduce assembly Ian guage from each and find the fun cti on n ames that are p roduced by your C fun cti on and your C+ member fun cti on, so you can see what sort of n am
18、e decorati on occurs in side the comp iler.Solutio n:For f(int) one compiler gen erated the name ?fYAXHZ , and ?fYAXNZ for f(double). Go figure.4-11Write a p rogram with con diti on ally-co mp iled code in main( ), so that whe n a prepro cessor value is defi ned one message is prin ted, but whe n it
19、 is not defi ned ano ther message is prin ted. Comp ile this code exp erime nting with a #define within the p rogram, the n discover the way your comp iler takes prep rocessor defi niti ons on the comma nd line and exp erime nt with that.(Left to the reader)4-12Write a p rogram that uses assert( ) w
20、ith an argume nt that is always false (zero) to see what happens when you run it. Now compile it with #define NDEBUG and run it again to see the differe nee.(Left to the reader)4-13Create an abstract data type that rep rese nts a videota pe in a video ren tal store. Try to con sider all the data and
21、 op erati ons that may be n ecessary for the Video type to work well with in the video ren tal man ageme nt system .In clude a p rint( ) member fun ctio n that dis pl ays in formatio n about the Video.(Left to the reader)4-14Create a Stack object to hold the Video objects from Exercise 13. Create se
22、veral Video objects, store them in the Stack, the n dis play them using Video: print().(Left to the reader)4-15Write a p rogram that prints out all the sizes for the fun dame ntal data types on your compu ter using sizeof().Solutio n:/: S04:Sizeof.c pp #in clude int mai n() using namespacestd;coutsi
23、zeof(char) en dl;coutsizeof(short) en dl;coutsizeof(i nt) en dl;coutsizeof(l ong) en dl;coutsizeof(float) en dl;coutsizeof(double) en dl;coutsizeof(long double) as its underlying data structure.(Left to the reader)4-17Dyn amically create pi eces of storage of the follow ing typ es, using new: int, l
24、ong, an array of 100 char s, an array of 100 float s. Print the addresses of these and the n free the storage usin gdelete.Solutio n:/: S04:Storage.c pp #in clude int mai n() using namespacestd;int* p_int = n ewi nt;long* p_long = new long;char* p_chars = new char100;float* p_floats = n ewfloat100;c
25、out p_int = p_int en dl;cout p_long = p_long en dl;cout p_chars = static_cas(p_chars) en dl;cout p_floats = p_floats en dl;delete p_int;delete p_lo ng;delete p_chars;delete p_floats;/* Out put: / Comp iler A:p_int = 00673384 p_long = 00673394 p_chars = 006733A4 p_floats = 0067340C / Com piler B: p_i
26、nt = 00770950 p_long = 00770940 p_chars = 007708D0 p_floats = 00770630 */ /:The static_cast above is n ecessary because the out put stream insertion op erator is overloaded to treat a char* as a null-terminated string. All other pointers have their addresses printed out in hexadecimal. Don t forget
27、to use the bracketb Welete for arrays. Notice that the way a comp iler allocates thi ngs on the stack is its bus in ess -do n t count on any com mon behavior across platforms.4-18Write a function that takes a char* argument. Using new, dynamically allocate an array ofchar that is the size of the cha
28、r array that s p assed to the function. Using array in dex ing, copy the characters from the argume nt to the dyn amically allocated array (don t forget the n ull term in ator)and return the pointer to the copy. In your main( ), test the function by passing a static quoted character array, the n tak
29、e the result of that and p ass it back into the fun cti on. Print both stri ngs and both poin ters so you can see they are differe nt storage. Using delete clea n up all the dyn amic storage.Solutio n:/: S04:Stri ngCo py.c pp#in elude #in elude #inelude / For size t using n ames pacestd;char* copy (
30、char* s1) size_t len 二 strle n(s1);char* s2 = new charle n + 1;strc py(s2, s1);return s2;int mai n() char* first = Read my lips;char* sec ond = copy (first);cout first = first at static_cas(first) en dl;cout second = second at static_cas(sec ond) : strlen to determ ine the length of the incoming str
31、ing, and strcpy to copy one string to another (including the null terminator). size_t is an unsigned integer type (usually unsigned int) defined in various places, including viostream, and is the return type of strlen. See the previous exercise for an explan ati on of the casts used.4-19Show an exa
32、mple of a structure declared with in ano ther structure (a n ested structure). Declare data members in both structs, and declare and defi ne member functions in both struct s. Write a main( ) that tests your new typ es.Solutio n:/: S04:Nested.c pp #in clude struct Outer int o;void setO(i nt n) o = n
33、;int getO() return o;struct Inner in t i;void setl(i nt n) i = n;int getl() return i;int mai n() using namespacestd;Outer o;o.setO(1);cout o.getO() en dl;Outer:l nner i;i.setl(2);cout i.getl() en dl;/* Out put:*/ /:Declari ng a struct with in a struct p laces the inner in the scope of the outer. For
34、 this reas on I have to use the expression Outer:lnner above. Nesting structures in this fashion shows an ownership relati onship betwee n types and also mini mizes the cha nee of n ame con flict in the global n ames pace.4-20How big is a structure? Write a piece of code that prints the size of vari
35、ous structures. Create structures that have data members only and ones that have data members and fun cti on members. Then create a structure that has no members at all. Print out the sizes of all these. Explain the reas on for the result of the structure with no data members at all.Solutio n:/: S04
36、:StructSize.c pp #in clude struct Data Only int x;struct Both int X;void setX(i nt);int getX();; struct Noth ing ; int mai n() using namespacestd;cout sizeof(Data Only) en dl;cout sizeof(Both) en dl;cout sizeof(Nothi ng) en dl;/* Out put:*/41/:As you can see in this p rogram, the p rese nee of a (no
37、n-virtual) member function does not affect the size of a struct. (NOTE: this is only true for classes with no virtual functions -see Chap ter 15). The sta ndard requires all struct s to have non-zero size, eve n if they have no members. This is so that dist inct objects of any type will have dist in
38、ct memory addresses.4-21C+ automatically creates the equivale nt of a typ edef for struct s, as you ve see n in this cha pter. It also does this for enu meratio ns and unions. Write a small p rogram that dem on strates this.(Left to the reader)4-22Create a Stack that holds Stashes. Each Stash will h
39、old five lines from an input file. Create the Stashes using new. Read a file into your Stack, then reprint it in its original form by extracting it from the Stack.(Left to the reader)4-23Modify Exercise 22 so that you create a struct that encapsulates the Stack of Stashes. The user should only add a
40、nd get lines via member functions, but under the covers the struct happens to use a Stack of Stashes.(Left to the reader)4-24Create a struct that holds an int and a poin ter to ano ther in sta nee of the same struct. Write a function that takes the address of one of these structs and an int in dicat
41、i ng the len gth of the list you want created. This function will make a whole chain of these structs (a linked list), starting from the argume nt (the head of the list), with each one pointing to the n ext. Make the new structs using new, and put the coun t (which object nu mber this is) in the int
42、 .In the last struct in the list, put a zero value in the pointer to indicate that it s the end. Write a second function that takes thehead of your list and moves through to the end, prin ti ng out both the poin ter value and the int value for each one.(Left to the reader)4-25Rep eat Exercise 24, bu
43、t put the functions in side a struct in stead of usingstmacts andfun ctio ns.Solutio n:/: S04:Li nkedList.c pp #in clude #in clude using n ames pacestd;struct Node int val;Node* n ext;void create(Node* head,i nt howMa ny) assert(head);Node* p1 = head;for (int i = 1; i val = i;p1-next = p2;p1 = p2;p1
44、-n ext = 0;void dis play(Node* no de) assert (no de);while (no de) cout val (at node n ext;void clea nup(N ode* no de) if (n ode) clea nup(no de-n ext);cout deleti ng Node at node val = 0;create(head, 10);dis play(head);clea nup (head);/* Out put: 0 (at 00770950)1 (at 00770940)2 (at 00770930)3 (at 00770920)4 (at 00770910)5 (at 00770900)6 (at 007708F0)7 (at 0077
溫馨提示
- 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)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 中標格式合同范本
- 省級課題申報書研究手段
- 買貓質(zhì)保合同范本
- 鳳爪貿(mào)易合同范本
- 烹飪課題申報書
- 2025生產(chǎn)設(shè)備大數(shù)據(jù)輕量化采集要求
- 單方面解約合同范本
- 產(chǎn)供銷合同范本
- 小學(xué)音樂類課題申報書
- 制作公司合同范本
- GGD交流低壓配電柜運行、維護說明書、安裝、操作手冊
- JCT2354-2016 衛(wèi)生陶瓷企業(yè)安全生產(chǎn)規(guī)范
- 2024年全國國家版圖(中小學(xué)組)知識競賽題庫及答案
- QBT 2605-2003 工業(yè)氯化鎂行業(yè)標準
- 2024年江西機電職業(yè)技術(shù)學(xué)院單招職業(yè)適應(yīng)性測試題庫帶答案
- 《拒絕沉迷手機遠離“垃圾快樂”》班會課件
- 普通高中政治課程標準測試題及答案
- 2024年知識競賽-《民用爆炸物品安全管理條例》知識競賽筆試參考題庫含答案
- 心肺復(fù)蘇基本生命支持技術(shù)(雙人)操作考核評分標準
- 屋頂 屋頂?shù)呐潘O(shè)計 屋頂?shù)呐潘绞剑ńㄖ?gòu)造)
- Web-of-sciencenew文獻檢索-課件
評論
0/150
提交評論