tailieunhanh - A Complete Guide to Programming in C++ part 52

A Complete Guide to Programming in C++ part 52. This book provides both novice and experienced programmers with a comprehensive resource manual for the C++ programming language. Readers gain experience in all aspects of programming, from elementary language concepts to professional software development, with in depth coverage of all the language elements en route. These elements are carefully ordered to help the reader create useful programs every step of the way. | ASSIGNMENT 489 Each class comprises four implicitly defined default methods which you can replace with your own definitions the default constructor and the destructor the copy constructor and the standard assignment In contrast to initialization by means of the copy constructor which takes place when an object is defined an assignment always requires an existing object. Multiple assignments which modify an object are possible. Default Assignment Given that v1 and v2 are two FloatArr class objects the following assignment is valid Example v1 v2 Possible but ok Default assignment is performed member by member. The data members of v2 are copied to the corresponding data members of v1 just like the copy constructor would copy them. However this technique is not suitable for classes with dynamic members. This would simply point the pointers belonging to different objects at the same dynamic allocated memory. In addition memory previously addressed by a pointer of the target object will be unreferenced after the assignment. Overloading the Assignment Operator In other words you need to overload the default assignment for classes containing dynamic members. Generally speaking if you need to define a copy constructor you will also need to define an assignment. The operator function for the assignment must perform the following tasks release the memory referenced by the dynamic members allocate sufficient memory and copy the source object s data to that memory. The operator function is implemented as a class method and returns a reference to the target object allowing multiple assignments. The prototype of the operator function for the FloatArr class is thus defined as follows FloatArr FloatArr operator const FloatArr src When implementing the operator function you must avoid self assignment which would read memory areas that have already been released. 490 CHAPTER 22 DYNAMIC MEMBERS EXERCISES New methods of class List Copy constructor List List const List Assignment List .

TỪ KHÓA LIÊN QUAN