tailieunhanh - A Complete Guide to Programming in C++ part 51
A Complete Guide to Programming in C++ part 51. 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. | MEMBERS OF VARYING LENGTH 479 Dynamic Members You can exploit the potential of dynamic memory allocation to leverage existing classes and create data members of variable length. Depending on the amount of data an application program really has to handle memory is allocated as required while the application is running. In order to do this the class needs a pointer to the dynamically allocated memory that contains the actual data. Data members of this kind are also known as dynamic members of a class. When compiling a program that contains arrays you will probably not know how many elements the array will need to store. A class designed to represent arrays should take this point into consideration and allow for dynamically defined variable length arrays. Requirements In the following section you will be developing a new version of the FloatArr class to meet these requirements and additionally allow you to manipulate arrays as easy as fundamental types. For example a simple assignment should be possible for two objects vl and v2 in the new class. Example v2 vi The object v2 itself and not the programmer will ensure that enough memory is available to accommodate the array v1. Just as in the case of fundamental types it should also be possible to use an existing object v2 to initialize a new object v3. Example FloatArr v3 v2 Here the object v3 ensures that enough memory is available to accommodate the array elements of v2. When an object of the FloatArr is declared the user should be able to define the initial length of the array. The statement Example FloatArr fArr 100 allocates memory for a maximum of 100 array elements. The definition of the FloatArr class therefore comprises a member that addresses a dynamically allocated array. In addition to this two int variables are required to store the maximum and current number of array elements. 480 CHAPTER 22 DYNAMIC MEMBERS CLASSES WITH A DYNAMIC MEMBER First version of class FioatArr Dynamic array of floats. .
đang nạp các trang xem trước