Array Bounds(Midterm exam)

来源:互联网 发布:ajax json数据处理 编辑:程序博客网 时间:2024/05/19 04:26



#include "myArray.h"#include <iostream>#include <string>#include <cstring>using namespace std;template <class T>myArray<T>::myArray(int elements) {    myArr = new T[100];    SetNULL();    size = elements;    startpos = 0;    endpos = elements-1;}template <class T>myArray<T>::myArray(int start, int end) {    if (start >= end)       throw string("Invalid start and end position..terminating..."); //throw的用法    size = end-start+1;    myArr = new T[100];    SetNULL();    startpos = start;    endpos = end;}template <class T>myArray<T>::~myArray() {    delete []myArr;}template <class T>void myArray<T>::SetNULL() {     for (int i = startpos; i <= endpos; i++)       myArr[i] = 0;}template <class T>T & myArray<T>::operator[](int i) {    if (i < startpos || i > endpos)       throw string("Element out of array bounds...nothing to be done");    else       return myArr[i]; //应该返回myArr[i-startpos],将任意数组移到0开头的正常数组}template <class T>ostream & operator<<(std::ostream & os, myArray<T> & arr) {         os << "{";         int i;         for (i = arr.startpos; i < arr.endpos; i++)           os << arr[i] << ",";  //一定要arr.myArr[i]         os << arr[i] << "}" << endl;         return os;}



0 0