c++自定义对象支持按下标遍历*

#include <iostream>
#include <string>
using namespace std;
class Array {
   public:
    Array() {
        length = 0;
        num = NULL;
    };

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

   private:
    int length;
    int* num;
};

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

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 < 6; i++) cout << A[i] << " ";
    } catch (string s) {
        cout << endl;
        cerr << s << ", i = " << i << endl;
    }

    cout << endl << "+++++++++++++" << endl << endl << endl;
    int aa = A[0];

    return 0;
}
posted @ 2021-10-29 13:02  邱明成  阅读(58)  评论(0编辑  收藏  举报