|
|
|
|
|
|
|
#include dynarray.h
#include <iostream.h>
int main()
{
int numElements; // Array size
int index; // Array index
cout << Enter the array size: ;
cin >> numElements;
DynArray x( numElements);
DynArray y(numElements);
for (index = 0; index << numElements; index++)
x. Store(index + 100, index);
y.CopyFrom(x);
for (index = 0; index << numElements; index++)
cout << y. ValueAt( index);
return 0;
} |
|
|
|
|
|
|
|
|
If the input value for numElements is 20, the class constructor creates a 20element array for x and initializes all elements to zero. Similarly, y is created with all 20 elements initialized to zero. After using the Store function to store 20 new values into x, the program does an aggregate copy of x to y using the CopyFrom operation. Then the program outputs the 20 elements of y, which should be the same as the values contained in x. Finally, both class objects go out of scope (because control exits the block in which they are declared), causing the class destructor to be executed for each object. Each call to the destructor deallocates a dynamic array from the free store, as we will see when we look at the implementations of the class member functions. |
|
|
|
|
|
|
|
|
Implementation of the Class: Next, we implement each class member function, placing the function definitions into a C++ implementation file dynarray.cpp. As we implement the member functions, we also discuss appropriate testing strategies. |
|
|
|
|
|
|
|
|
The class constructor and destructor: According to the specification file, the class constructor should allocate an array of size arrSize, and the destructor should deallocate the array. The constructor must also do some error checking; it must verify arrSize is at least 1, and that allocating the dynamic data succeeded. If both of these conditions are met, the constructor sets each array element to zero. |
|
|
|
|
|