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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
|
// CS 540, Test Prog 4, Bob Hart
#include <iostream>
#include <new>
#include <string>
#include <cstdlib>
using namespace std;
class Arr {
public:
Arr(unsigned els);
Arr(const Arr & other); // you didn't have to write a copy ctor
~Arr();
unsigned getSize() const;
void set(unsigned index, int value);
int get(unsigned index) const;
friend ostream & operator<<(ostream & out, const Arr & ar);
void grow(unsigned newEls);
Arr & operator=(const Arr & rhs);
private:
// helper func allocates array & initializes to 0's
static int * alloc(unsigned els);
int * _data;
unsigned _els;
}; // class Fraction
bool die(const string & msg);
int main()
{
Arr ar(3);
ar.set(0, 10), ar.set(1, 11), ar.set(2, ar.get(1)); // {10, 11, 11}
ar.grow(5); // {10, 11, 11, 0, 0}
Arr arr2(1234);
arr2 = ar;
Arr arr3(arr2);
cout <<"{ 10 11 11 0 0} == " <<arr3 <<endl;
}
Arr::Arr(unsigned els): _data(alloc(els)), _els(els)
{}
Arr::Arr(const Arr & other): _data(alloc(other._els)), _els(other._els)
{
for(unsigned i = 0; i < _els; i++)
_data[i] = other._data[i];
}
Arr::~Arr()
{ delete[] _data; cout <<"d"; }
unsigned Arr::getSize() const
{ return _els; }
void Arr::set(unsigned index, int value)
{ _data[index] = value; }
int Arr::get(unsigned index) const
{ return _data[index]; }
ostream & operator<<(ostream & out, const Arr & ar)
{
out <<"{";
for(unsigned i = 0; i < ar._els; i++)
out <<" " <<ar._data[i];
return out <<"}";
}
void Arr::grow(unsigned newEls)
{
int * newData = alloc(newEls);
for(unsigned i = 0; i < _els; i++)
newData[i] = _data[i];
delete[] _data; cout <<"d";
_data = newData;
_els = newEls;
}
Arr & Arr::operator=(const Arr & rhs)
{
if(this != &rhs) {
delete[] _data; cout <<"d";
_data = alloc(_els = rhs._els);
for(unsigned i = 0; i < _els; i++)
_data[i] = rhs._data[i];
}
return *this;
}
int * Arr::alloc(unsigned els)
{
int * ret = nullptr;
try {
ret = new int[els]();
} catch(const bad_alloc &) {
die("Arr: allocation failure");
}
cout <<"n";
return ret;
}
bool die(const string & msg)
{
cout <<"Fatal error: " <<msg <<endl;
exit(EXIT_FAILURE);
}
|