safearray.h

来自「ssd5 数据结构与算法 EXAM1 敬请参考下」· C头文件 代码 · 共 51 行

H
51
字号
#ifndef SAFEARRAY_H
#define SAFEARRAY_H

using namespace std;

template <class T>
class SafeArray {

protected:
    T *storage;
    int count;

public:
    SafeArray();
    SafeArray(int);
    virtual ~SafeArray(void);
    virtual T& operator[] (int) throw(out_of_range);
};

// default constructor
template <class T>
SafeArray<T>::SafeArray () : storage(NULL), count(0) {}

// single param constructor
template <class T>
SafeArray<T>::SafeArray (int count) : storage(new T[count]), count(count) {}

// destructor
template <class T>
SafeArray<T>::~SafeArray(void) {
    delete [] storage;
}

// overloaded [] operator
template <class T>
T& SafeArray<T>::operator[] (int index) throw (out_of_range) {

    if (index < 0) {
        throw out_of_range("Index is below 0");
    }

    if (index >= count) {
        throw out_of_range("Index is too high");
    }

    return storage[index];
}


#endif

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?