11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

380Part VI: The Part of Tensclass Array{public:Array(int s){size = 0;pData = new int[s];if (pData){size = s;}}~Array(){delete pData;size = 0;pData = 0;}//either return or set the array dataint data(int index){return pData[index];}int data(int index, int newValue){int oldValue = pData[index];pData[index] = newValue;return oldValue;}protected:int size;int *pData;};The function data(int) allows the application software to read data out ofArray. This function is too trusting; it assumes that the index provided iswithin the data range. What if the index is not? The function data(int,int) is even worse because it overwrites an unknown location.What’s needed is a check to make sure that the index is in range. In the following,only the data(int) function is shown for brevity:int data(unsigned int index){if (index >= size){throw Exception(“Array index out of range”);}return pData[index];}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!