如何在类数组中的运算符 [] 中捕获异常

How to catch an Exception in operator[] in class Array?

本文关键字:运算符 捕获异常 数组      更新时间:2023-10-16

我必须试一试...捕获此函数,但我不知道如何继续该程序:通过显示 a[size] 在捕获异常后显示数组。

请帮助我。

对不起,我的英语不好。

这是我的程序...非常感谢。。。

#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 < 0n";
        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;
}

当你有一个声明为的函数时:

T& operator[](int index) throw(int);

预计会引发异常。不需要有一个 try/catch 块来抛出异常并处理异常。

您的实现可以是:

template<class T>
T& Array<T>::operator[](int index) throw(int){
   // Check whether the index is valid.
   // If it is not, throw an exception.
   if(index < 0  || index >= size)
      throw index;
   // The index is valid. Return a reference
   // to the element of the array.
   return a[index];
}

该功能的用户将被要求使用try/catch块。

Array<int> a;
try 
{
   int e = a[5]; // This call will throw an exception.
}
catch (int index)
{
   // Deal with out of bounds index.
}