I am having a problem with overloading and an assignment.
Here's the question
Design the class myArray that solves the array index out of bound problem, and also allows the user to begin the array index starting at any integer, positive or negative. Every object of type myArray is an array of type int. During execution, when accessing an array component, if the index is out of bounds, the program must terminate with an appropriate error message. Consider the following statements:
myArray<int> list(5);
myArray<int> myList(2, 13);
myArray<int> yourList(-5,9);
the statement in line 1 declares a list to be an array of 5 elements, the element type is int, and the elements start from list[0] .... list [4]. Line 2 declares a list of 11 elements, starting at myList[2] ... myList[12]. Line 3 declares a list of 14 elements, starting at myList[-5] ... myList[8]. Write a program to test your class
This is what I have so far from looking around. But I am confused and don't really know what to do from here. I could really use help on what to do. Thanks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
#include <iostream>
#include <cstdlib>
using namespace std;
template <class arrayTemp>
class myArray
{
friend std::ostream& operator<<(std::ostream& osObject, myArray<arrayTemp>& arr);
protected:
//template
arrayTemp *myArrayTemp;
//variables
int *arraySize;
int arrayStart;
int arrayEnd;
public:
//constructors
myArray(int elements);
myArray(int start, int end);
//function
void SetNULL();
//overloading operator []
arrayTemp& operator[](int i);
//display
void getOutput();
};
template <class arrayTemp>
arrayTemp& myArray<arrayTemp>::operator[](int i)
{
if(i > arraySize)
{
cout << "Array out of bounds: " <<endl;
}
else if(arrayStart == 0)
{
return myArrayTemp[i];
}
else
{
return myArrayTemp[(arrayStart + (i - 1))];
}
}
template <class arrayTemp>
myArray<arrayTemp>::myArray(int elements):
arraySize(elements), arrayStart(0), arrayEnd(elements)
{
myArrayTemp = new arrayTemp[arraySize];
SetNULL();
}
template <class arrayTemp>
myArray<arrayTemp>::myArray(int start, int end):
arrayStart(start)
arrayEnd(end)
{
if(start > end)
{
cout << "Invalid start position: " << endl;
}
else
{
arraySize = end - start;
}
myArrayTemp = new arrayTemp[arraySize];
SetNULL();
}
template <class arrayTemp>
void myArray<arrayTemp>::SetNULL()
{
for(int i = 0; i < arraySize; i++)
{
myArrayTemp[i] = (arrayTemp)0;
}
}
int main()
{
}
|