I have to make a try...catch in this function but i don't know how to continue the program: Display the array after catch an exception by displaying a[size].
Please help me.
Sorry for my bad English.
Here is my program... Thank you so much...
#include <iostream>
using namespace std;
namespace arr{
template<class T>
class Array{
private:
int size;
T* a;
public:
Array<T>();
Array<T>(int max);
~Array<T>();
T& operator[](int index) throw(int);
T& operator=(const T& a2);
void set(int index, T val);
void Display();
int GetSize();
void Sort();
T Max();
};
}
using namespace arr;
template<class T>
Array<T>::Array(){
size=0;
a=new T[0];
}
template<class T>
Array<T>::Array(int max){
size=max;
a=new T[size];
}
template<class T>
Array<T>::~Array(){
size=0;
delete[] a;
}
template<class T>
T& Array<T>::operator[](int index) throw(int){
try{
if(index>=0 && index <size)
return a[index];
else
throw(index);
} catch(int e){
cout<<"Exception Occured: ";
if(e<0)
cout<<"index < 0\n";
else
cout<<"index >= "<<size<<endl;
exit(1);
}
}
template<class T>
T& Array<T>::operator=(const T& a2){
for(int i=0;i<a2.GetSize();i++) set(i,a2[i]);
return *this;
}
template<class T>
void Array<T>::set(int index, T val){
a[index]=val;
}
template<class T>
void Array<T>::Display(){
for(int i=0;i<size;i++)
cout<<a[i]<<" ";
cout<<endl;
}
template<class T>
int Array<T>::GetSize(){
return size;
}
template<class T>
void Array<T>::Sort(){
for(int i=0;i<size-1;i++)
for(int j=i+1;j<size;j++)
if(a[i]>a[j]){
T tmp=a[i];
a[i]=a[j];
a[j]=tmp;
}
}
template<class T>
T Array<T>::Max(){
T m=a[0];
for(int i=1;i<size;i++)
if(a[i]>m) m=a[i];
return m;
}
int main(){
int size=0;
cout<<"Size of Array: ";
cin>>size;
Array<int> a(size);
for(int i=0;i<size;i++){
int tmp;
cout<<"a["<<i+1<<"]=";
cin>>tmp;
a.set(i,tmp);
}
cout<<a[size]<<endl; //Test Exception.
cout<<"Your Array:\n";
a.Display();
return 0;
}