C++编程思想 答案 第五章 其他章节请点击用户名找 thinking in C++ annotated solution guide(charpter 5)..doc_第1页
C++编程思想 答案 第五章 其他章节请点击用户名找 thinking in C++ annotated solution guide(charpter 5)..doc_第2页
C++编程思想 答案 第五章 其他章节请点击用户名找 thinking in C++ annotated solution guide(charpter 5)..doc_第3页
C++编程思想 答案 第五章 其他章节请点击用户名找 thinking in C++ annotated solution guide(charpter 5)..doc_第4页
C++编程思想 答案 第五章 其他章节请点击用户名找 thinking in C++ annotated solution guide(charpter 5)..doc_第5页
已阅读5页,还剩18页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

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 Allison2001 MindView, Inc. All Rights Reserved. Previous Chapter Table of Contents Next Chapter Chapter 55-1Create a class with public, private, and protected data members and function members. Create an object of this class and see what kind of compiler messages you get when you try to access all the class members.(Left to the reader)5-2Write a struct called Lib that contains three string objects a, b, and c. In main( ) create a Lib object called xand assign to x.a, x.b, and x.c. Print out the values. Now replace a, b, and c with an array of string s3. Show that your code in main( ) breaks as a result of the change. Now create a class called Libc, with private string objects a, b, and c, and member functions seta( ), geta( ), setb( ), getb( ), setc( ), and getc( ) to set and get the values. Write main( ) as before. Now change the private string objects a, b, and c to a privatearray of string s3. Show that the code in main( ) does not break as a result of the change.(Left to the reader)5-3Create a class and a global friend function that manipulates the private data in the class.(Left to the reader)5-4Write two classes, each of which has a member function that takes a pointer to an object of the other class. Create instances of both objects in main( ) and call the aforementioned member function in each class.Solution:/: S05:PointToMeAndYou.cpp#include using namespace std;class You; / Forward declarationclass Me public: void ProcessYou(You* p) cout Processing You at p endl; ;class You public: void ProcessMe(Me* p) cout Processing Me at p endl; ;int main() Me me; You you; me.ProcessYou(&you); you.ProcessMe(&me);/* Output:Processing You at 0065FDF4Processing Me at 0065FDFC*/:When two classes refer to each other, it is necessary to forward-declare at least one of them, as I did above. You must only use pointers, of course, or youll truly find yourself in a chicken-and-egg fix. FYI: when classes have a relationship, for example, and Employee “has-a” Manager, it is common to reflect this relationship by actually storing a pointer to the Manager object as a member in the Employee object, so you dont have to explicitly pass pointers as arguments to member functions like I did here.5-5Create three classes. The first class contains privatedata, and grants friendship to the entire second class and to a member function of the third class. In main( ), demonstrate that all of these work correctly.Solution:/: S05:MyFriends.cpp#include using namespace std;class HasStuff; / Must precede GoodFriend definitionclass GoodFriend / Must precede HasStuff definitionpublic: void hasAccess(HasStuff* p); void hasNoAccess(HasStuff* p) cout Cannot access p endl; ;class HasStuff private: int x; friend class BestFriend; friend void GoodFriend:hasAccess(HasStuff*);/ Must follow HasStuff definition:void GoodFriend:hasAccess(HasStuff* p) cout From GoodFriend:hasAccess: x x = 5; void queryFriend(HasStuff* p) cout From BestFriend: x endl; ;int main() HasStuff h; BestFriend b; b.initFriend(&h); b.queryFriend(&h); GoodFriend g; g.hasAccess(&h); g.hasNoAccess(&h);/* Output:From BestFriend: 5From GoodFriend:hasAccess: 5Cannot access 0065FE00*/:This is another exercise in forward declarations. The definition of GoodFriend requires the existence of class HasStuff, but I cannot include the implementation of GoodFriend:has Access( ) in situ, because it uses the fact that HasStuff contains an integer named x (likewise for the entire class BestFriend). Also, if you tried to access HasStuff:x in GoodFriend:hasNoAccess( ) you would get a compiler error. The statement “friend class BestFriend” inside of HasStuff is simultaneously a forward declaration and a friend declaration, otherwise I would have had to forward-declare BestFriend before the definition of HasStuff (but Im lazy).5-6Create a Hen class. Inside this, nest a Nest class. Inside Nest, place an Egg class. Each class should have a display( ) member function. In main( ), create an instance of each class and call the display( ) function for each one.Solution:/: S05:NestedFriends.cpp#include using namespace std;class Hen public: void display() cout Hen:displayn; class Nest public: void display() cout Hen:Nest:displayn; class Egg public: void display() cout Hen:Nest:Egg:displayn; ; ;int main() Hen h; Hen:Nest n; Hen:Nest:Egg e; h.display(); n.display(); e.display();/* Output:Hen:displayHen:Nest:displayHen:Nest:Egg:display*/:Nest and Egg are just like normal classes except they reside in the scope of other classes instead of the global scope, which explains the need for the explicit qualification via the scope resolution operator. Also, Hen has no access rights to any private members of Nest or Egg, nor does Nest have any rights to Eggs private members (if there were any see the next exercise).5-7Modify Exercise 6 so that Nest and Egg each contain private data. Grant friendship to allow the enclosing classes access to this private data.Solution:/: S05:NestedFriends.cpp#include using namespace std;class Hen public: class Nest int x; friend class Hen; public: class Egg int y; friend class Nest; public: void display() cout Hen:Nest:Egg:display: y y = 2; void display() cout Hen:Nest:display: x x = 1; void display() cout Hen:displayn; ;int main() Hen h; Hen:Nest n; Hen:Nest:Egg e; h.initNest(&n); n.initEgg(&e); h.display(); n.display(); e.display();/* Output:Hen:displayHen:Nest:display: 1Hen:Nest:Egg:display: 2*/:In this example I had to move the implementation of Hen:Nest:display( ) past the nested class Egg, because it access members of Egg. The same reasoning applies to the init-functions above.5-8Create a class with data members distributed among numerous public, private, and protected sections. Add a member function showMap( ) that prints the names of each of these data members and their addresses. If possible, compile and run this program on more than one compiler and/or computer and/or operating system to see if there are layout differences in the object.Heres a sample for two particular compilers:Solution:/: S05:MapMembers.cpp#include using namespace std;class Mapped int x; protected: int y;public: int z; void showMap() cout x is at &x endl; cout y is at &y endl; cout z is at &z endl; ;int main() Mapped m; m.showMap();/* Output:/ Compiler A:x is at 0065FDF8y is at 0065FDFCz is at 0065FE00/ Compiler B:x is at 0064FDECy is at 0064FDF0z is at 0064FDF4*/:5-9Copy the implementation and test files for Stashin Chapter 4 so that you can compile and test Stash.h in this chapter.(Left to the reader)5-10Place objects of the Hen class from Exercise 6 in a Stash. Fetch them out and print them (if you have not already done so, you will need to add Hen:print( ).(Left to the reader)5-11Copy the implementation and test files for Stackin Chapter 4 so that you can compile and test Stack2.h in this chapter.(Left to the reader)5-12Place objects of the Hen class from Exercise 6 in a Stack. Fetch them out and print them (if you have not already done so, you will need to add Hen:print( ).(Left to the reader)5-13Modify Cheshire in Handle.cpp, and verify that your project manager recompiles and relinks only this file, but doesnt recompile UseHandle.cpp.(Left to the reader)5-14Create a StackOfInt class (a stack that holds ints) using the “Cheshire cat” technique that hides the low-level data structure you use to store the elements in a class called StackImp. Implement two versions of StackImp: one that uses a fixed-length array of int, and one that uses a vector. Have a preset maximum size for the stack so you dont have to worry about expanding the array in the first version. Note that the StackOfInt.h class doesnt have to change with StackImp.Solution:Heres the StackOfInt class:/: S05:StackOfInt.h#include / for size_t#include / for INT_MIN/ VC+ doesnt put size_t in std:#ifndef _MSC_VERusing std:size_t;#endifstruct StackImp; / Incomplete type declarationstruct StackOfInt enum STKERROR = INT_MIN; void init(); void cleanup(); int push(int); int pop(); int top(); size_t size();private: StackImp* pImpl; / The “smile”;/:To do Cheshire Cat, I just declare the StackImp class (this makes it an “incomplete” type), and declare a pointer to it as a member of StackOfInt. The implementations of StackOfInts member functions will use the internals of StackImp via pImpl, so I have to define the method bodies in a separate .cpp file (otherwise were not hiding anything!). Heres the .cpp file for the array version:/: S05:StackOfInt1.cpp O/ Uses an array to implement a stack#include StackOfInt.h/ Complete the incomplete type StackImp:/ (This could be in a separate header file)struct StackImp enum MAXSIZE = 100; int dataMAXSIZE; int ptr;void StackOfInt:init() pImpl = new StackImp;int StackOfInt:push(int x) if (pImpl-ptr = StackImp:MAXSIZE) return STKERROR; else pImpl-datapImpl-ptr+ = x; return x; int StackOfInt:pop() return (pImpl-ptr = StackImp:MAXSIZE) ? STKERROR : pImpl-data-pImpl-ptr;int StackOfInt:top() return (pImpl-ptr = StackImp:MAXSIZE) ? STKERROR : pImpl-datapImpl-ptr-1;size_t StackOfInt:size() return pImpl-ptr;void StackOfInt:cleanup() delete pImpl;/:First off I complete the definition of StackImp, then implement the methods of StackOfInt. The most important thing to do is create StackOfInts StackImp member on the heap, so the user must call the init( ) before using the stack functions, and must remember to call cleanup( ) when finished. (All of this is taken care of automatically by a constructor and a destructor, as explained in the nest chapter). Heres a sample test program:/: S05:StackOfIntTest.cpp/L StackOfInt1#include StackOfInt.h#include int main() using namespace std; StackOfInt stk; stk.init(); for (int i = 0; i 0) cout stk.pop() endl;/* Output:43210*/:Heres the vector version:/: S05:StackOfInt2.cpp O/ Uses a vector to implement a stack#include StackOfInt.h#include using namespace std;/ Complete the incomplete type StackImp:/ (This could

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论