C++重载下标操作符[](一)

#include <iostream>
#include<string>

using namespace std;

class Array{
public:
    Array(){length=0;num=NULL;};
    Array(int );

    int &operator[](int );
    const int &operator [](int ) const;
    int getlength() const {return length;};

private:
    int length;
    int *num;
};

Array::Array(int n) {
    try{
        num=new int [n];
    }
    catch(bad_alloc)
    {
        cerr<<"allocate storage failure"<<endl;
        throw;
    }
    length =n;
}

int &Array::operator[](int i)  {
    if (i<0 || i>length)
        throw string("out of bounds");
    return num[i];

}

const int &Array::operator[](int i) const {
    if (i<0 || i>length)
        throw string("out of bounds");
    return num[i];

}


int main(){
    Array A(5);

    int i ;
    try{
        for (i=0;i<A.getlength();i++)
            A[i]=i;
        for (i=0;i<6;i++)
            cout<<A[i]<<endl;
    }
    catch (string s)
    {
        cerr<<s<<",i ="<<i<<endl;
    }

    return 0;

}
posted @ 2022-08-19 22:47  luoganttcc  阅读(9)  评论(0)    收藏  举报