Thanks MiiNiPaa for your prompt reply. Let me try to respond:
You wrote: "What if lower bound is 9 and upper bound is 100? You will create an array of size 1, but will try to access 99th element."
Did you mean to write 10 and not 100? 'Cause that's the only way the array size would result in 1.
Also you wrote: "Also problem with negative elements." Did you mean negative elements of the array OR negative parameters at object declaration? Anyways, the index of arrayPtr (= i) can never be negative, given some object declaration constraint (e.g. upperBound>lowerBound) and the way I wrote the constructor.
The constructor is definitely not the problem; like I implied in my earlier post, the objects of the class were successfully created (for integer, double, and string datatypes); it's the assignment operation that's failing me, I'm guessing. Here are my constructor and the overloaded operator[] you asked for:
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
|
template<class dataType>
myArray<dataType>::myArray(int lowerBound, int upperBound)
{
int arraySize;
if (upperBound == 0)
{
arrayLowerBound = 0;
arrayUpperBound = lowerBound;
}
else
{
arrayLowerBound = lowerBound;
arrayUpperBound = upperBound;
}
arraySize = arrayUpperBound - arrayLowerBound;
arrayPtr = new dataType[arraySize];
}
template<class dataType>
dataType& myArray<dataType>::operator[](int index)
{
if (arrayLowerBound <= index && index < arrayUpperBound)
return arrayPtr[index];
else
{
cout<<"Array index out of bound!! Bailing out!"<<endl<<endl<<endl;
// wait until user is ready before terminating program
system("PAUSE");
abort(); //terminates program due to erroneous array index
}
assert(arrayLowerBound <= index && index < arrayUpperBound);
return arrayPtr[index];
}
|
By the way, I'm jealous of the way you captured the exact fonts/color of my program segment. Yours even had line numbers! So cool! How do I go about doing that on here; I'm fairly new to the forum. Thanks.