Sams Teach Yourself C++ in 21 Days

(singke) #1
Handling Errors and Exceptions 743

20


9: public:
10: // constructors
11: Array(int itsSize = DefaultSize);
12: Array(const Array &rhs);
13: ~Array() { delete [] pType;}
14:
15: // operators
16: Array& operator=(const Array<T>&);
17: T& operator[](int offSet);
18: const T& operator[](int offSet) const;
19:
20: // accessors
21: int GetitsSize() const { return itsSize; }
22:
23: // friend function
24: friend ostream& operator<< (ostream&, const Array<T>&);
25:
26: // define the exception classes
27:
28: class xSize {};
29:
30: private:
31: int *pType;
32: int itsSize;
33: };
34:
35: template <class T>
36: Array<T>::Array(int size):
37: itsSize(size)
38: {
39: if (size <10 || size > 30000)
40: throw xSize();
41: pType = new T[size];
42: for (int i = 0; i<size; i++)
43: pType[i] = 0;
44: }
45:
46: template <class T>
47: Array<T>& Array<T>::operator=(const Array<T> &rhs)
48: {
49: if (this == &rhs)
50: return *this;
51: delete [] pType;
52: itsSize = rhs.GetitsSize();
53: pType = new T[itsSize];
54: for (int i = 0; i < itsSize; i++)
55: pType[i] = rhs[i];
56: }

LISTING20.9 continued

Free download pdf