IntArray.h
#include <iostream>
using namespace std;
const int array_size = 12;
class IntArray
{
public:
IntArray(int sz = array_size);
IntArray(const int* copy_from, int len);
void dump(void);
IntArray scale(int factor);
IntArray(const IntArray&); // copy xtor
~IntArray() { delete [] ia; } // need []?
IntArray& operator=(const IntArray&); // must be const?
int& operator[](int);
int getSize() { return size;}
protected:
void init(const int* copy_from, int size);
int size;
int *ia;
}; //this semi really goes with 'class IntArray
IntArray.cpp
#include "IntArray.h"
/* use 'iostream' and the namespace statement instead of 'iostreams.h'
*/
#include <iostream>
using namespace std;
/* xtor: note, default for 'size_in' is in the definition!
*/
IntArray::IntArray(int size_in)
{ init(NULL, size_in);
}
IntArray::IntArray(const IntArray& base)
{ init(base.ia, base.size);
}
/* Note, with icc and gcc the local is returned! A copy is not made of
* 'temp'! Handy!
*/
IntArray IntArray::scale(int factor)
{ IntArray temp(*this); // make a copy
for (int i = 0; i < size; i++)
{ temp[i] *= factor;
}
return temp;
}
IntArray& IntArray::operator=(const IntArray& base)
{ if (&base != this) // don't assign to myself!
{ delete [] ia;
init(base.ia, base.size);
}
return *this;
}
/* initializer used by xtors
*/
void IntArray::init(const int* array, int size_in)
{ size = size_in;
ia = new int(size); // 'new int[size]' also works
assert(ia !=0); // chack if alloc failed
// initialize to passed-in array or '0' if none
for (int i = 0; i < size; i++)
{ ia[i] = (array == NULL) ? 0 : array[i];
} }
/* plain text dump
*/
void IntArray::dump()
{ if (size == 0)
{ printf("<empty>");
}
for (int i = 0; i < size; i++)
{ cout << ia[i] << ", ";
}
cout << endl;
}
/* Note this works BOTH was a read and write! It's as if a reference
* can be a l- or r-value. If this is called like 'foo = bar[2]', then
* it simply returns the integer. If it's 'bar[2] = foo', then it
* returns an assignable reference that gets plopped in for 'bar[2] which
* then gets the equals treatment.
*/
int& IntArray::operator[](int index)
{ return ia[index];
}
int main(void)
{
IntArray a = IntArray(3);
a[0] = 12;
a[1] = 34;
a[2] = 56;
a.dump();
IntArray b = IntArray(a);
b.dump();
b[0] = 78;
b[1] = 90;
b[2] = 12;
b.dump();
IntArray c;
c = a;
c.dump();
c = b;
c.dump();
IntArray* t = new IntArray(b);
/* check for memory leaks
*/
while(1)
{
*t = b;
t->dump();
cout << endl;
*t = a;
t->dump();
cout << endl;
}
delete t;
}
--
MattWalsh - 03 May 2005