1 #include<iostream> 2 #include<cmath> 3 #include<cstdio> 4 using namespace std; 5 template <typename T, int capacity> 6 class Array 7 { 8 public: 9 Array(); 10 ~Array(); 11 bool empty(); 12 void push(T value); 13 T pop(); 14 int size(); 15 T& operator[] (int index); 16 private: 17 T* elements; 18 int num; 19 }; 20 21 class ArrayException 22 { 23 public: 24 ArrayException(const char *msg); 25 const char *what() const; 26 private: 27 const char *message; 28 }; 29 30 31 32 33 34 template <typename T, int capacity> 35 Array<T,capacity>::Array(){ 36 num = 0; 37 elements = new T[capacity]; 38 } 39 template <typename T, int capacity> 40 Array<T,capacity>::~Array(){ 41 delete [] elements; 42 } 43 template <typename T, int capacity> 44 bool Array<T,capacity>::empty(){ 45 if(num==0) return true; 46 else return false; 47 } 48 template <typename T, int capacity> 49 void Array<T,capacity>::push(T value){ 50 if(num >= capacity) throw ArrayException("Array Full Exception"); 51 else { 52 elements[num] = value; 53 num++; 54 } 55 } 56 template <typename T, int capacity> 57 T Array<T,capacity>::pop(){ 58 if(num == 0) throw ArrayException("Array Empty Exception"); 59 else { 60 T temp = elements[num-1]; 61 elements[num-1] = 0; 62 num--; 63 return temp; 64 } 65 } 66 67 template <typename T, int capacity> 68 int Array<T,capacity>::size(){ 69 return num; 70 } 71 template <typename T, int capacity> 72 T& Array<T,capacity>::operator[] (int index){ 73 if(index < 0 || index >= num) throw ArrayException("Out of Range Exception"); 74 else return elements[index]; 75 } 76 ArrayException::ArrayException(const char *msg){ 77 message=msg; 78 } 79 const char* ArrayException::what() const{ 80 return message; 81 82 } 83 84 85 void test() 86 { 87 Array<int,1> intArray; 88 89 try { 90 intArray.push(1); 91 } 92 catch (ArrayException ex) { 93 cout << ex.what() << endl; 94 } 95 try { 96 cout << intArray[3] << endl; 97 } 98 catch (ArrayException ex) { 99 cout << ex.what() << endl; 100 } 101 try { 102 cout << intArray.pop() << endl; 103 } 104 catch (ArrayException ex) { 105 cout << ex.what() << endl; 106 } 107 } 108 int main(){ 109 110 111 Array<int,15> a; 112 for (int i = 0; i <15; i++) a.push(i); 113 cout<<"a.size=="<<a.size()<<endl; 114 cout<<"a[0]=="<<a[0]<<endl; 115 cout<<"a[a.size()-1]=="<<a[a.size()-1]<<endl; 116 cout<<"a[-1]=="<<a[-1]<<endl; 117 cout<<"a[a.size()]=="<<a[a.size()]<<endl; 118 cout << endl; 119 120 return 0; 121 122 }