#include using namespace std ; #include "myArray.h" const int INIT_CAP = 10 ; myArray::myArray() { // default constructor cerr << "myArray default constructor called: " << this << endl; cap = INIT_CAP ; len = 0 ; data = new int[cap] ; } myArray::myArray(int n) { // constructor cerr << "myArray constructor called: " << this << endl; cap = n ; len = 0 ; data = new int[cap] ; } myArray::myArray(const myArray& B) { cerr << "myArray copy constructor called: " << this << endl ; cap = B.cap ; len = B.len ; data = new int[cap] ; for (int i=0 ; i < len ; i++) { data[i] = B.data[i] ; } } myArray& myArray::operator=(const myArray& B) { cerr << "myArray = operator called: " << this << endl ; cap = B.cap ; len = B.len ; delete[] data ; // release old memory. *** important *** data = new int[cap] ; for (int i=0 ; i < len ; i++) { data[i] = B.data[i] ; } return *this ; } myArray::~myArray() { // destructor cerr << "myArray destructor called: " << this << endl; delete [] data ; len = 0 ; } unsigned int myArray::length() const { return len ; } int& myArray::operator[](unsigned int i) { if (i >= len) { cerr << "index out of bounds\n" ; abort() ; } return data[i] ; } myArray myArray::operator+(const myArray& rhs) const { myArray temp ; temp.len = len + rhs.len ; temp.cap = temp.len ; temp.data = new int[temp.cap] ; for (int i=0 ; i < len ; i++) { temp.data[i] = data[i] ; } for (int j=len ; j < temp.len ; j++) { temp.data[j] = rhs.data[j - len] ; } cerr << " *** debug temp = " << &temp << endl ; temp.print() ; cerr << "temp.len = " << temp.len << endl; cerr << "temp.cap = " << temp.cap << endl; return temp ; } void myArray::append(int a) { if ( len < cap ) { // still have room data[len] = a ; len++ ; } else if ( len == cap ) { // save pointer to orig array int *temp = data ; // make new array cap = 2 * cap ; // cap != 0 data = new int[cap] ; // copy from old array for (int i=0; i cap. Not supposed to happen!\n" ; abort() ; } } void myArray::print(ostream& out) const { if (len < 1) { out << "[ ]" << endl ; return ; } out << "[" << data[0] ; for (int i=1; i < len ; i++) { out << ", " << data[i] ; } out << "]" << endl ; } // creates new myArray with items // from data[start], .., data[end-1] // inclusive. myArray myArray::slice(int start, int end) { cerr << "Entering myArray::slice()\n"; myArray B(end-start) ; B.len = B.cap ; for(int i = start; i < end ; i++) { B.data[i-start] = data[i] ; } return B ; // *** danger *** } // Not member functions!! ostream& operator<<(ostream& out, const myArray& A) { A.print(out) ; return out ; }