zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

C++ 重载 操作符 下标
2023-09-14 09:09:31 时间
#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;

}