Hey, all. Sorry to return so soon, but I need help. Here is my assignment.
Recall that in C++, there is no check on an array index out of bounds.
However, during program execution, an array index out of bounds can
cause serious problems. Also, in C++, the array index starts at 0.
Design and implement the class myArray that solves the array index out
of bounds 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); //Line 1
myArray<int> myList(2, 13); //Line 2
myArray<int> yourList(-5, 9); //Line 3
The statement in Line 1 declares list to be an array of 5 components, the
component type is int, and the components are: list[0], list[1], ...,
list[4]; the statement in Line 2 declares myList to be an array of 11 components,
the component type is int, and the components are: myList[2],
myList[3], ..., myList[12]; the statement in Line 3 declares yourList
to be an array of 14 components, the component type is int, and the
components are: yourList[-5], yourList[-4], ..., yourList[0],
..., yourList[8]. Write a program to test the class myArray.
Here is the header for my program.
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
|
#pragma once
#ifndef myArray_H
#define myArray_H
#include <iostream>
using namespace std;
template <class arrayType>
class myArray{
public:
myArray();
myArray(int, int);
~myArray();
int &operator[](int index);
void setArray();
private:
int *arrayList;
int size;
int start;
int finish;
};
template <class arrayType>
myArray<arrayType>::myArray(int index, int arraySize)
{
size = (arraySize - index);
arrayList = new int[size];
start = index;
finish = arraySize;
}
template <class arrayType>
int &myArray<arrayType>::operator[](int i)
{
if (i < start || i >= finish)
{
cout << "Error: Subscript " << i << " out of range" << endl;
system("pause");
exit(1);
}
return arrayList[i];
}
template <class arrayType>
void myArray<arrayType>::setArray()
{
for (int i = start; i < finish; i++)
{
arrayList[i] = 0;
}
}
template <class arrayType>
myArray<arrayType>::~myArray()
{
delete [] arrayList;
}
#endif
|
I thought that I was doing ok. The subscript array overload worked fine, but I can't seem to assign values into negative arrays without getting a heap corruption error. Any ideas what went wrong?