| 发表于:2007-03-27 17:34:021楼 得分:0 |
#include <iostream> // 仅用于测试时输出,数组类本身不需要 template <typename type> class array { public: typedef unsigned int size_tp; // 数组的尺寸(下标)类型 array(size_tp size = 0, type t = type()); // 可以用size指定初始大小,t指定初始值 array(const array& array); ~array(); // 空间自动释放 type& operator[](size_tp index); // 下标访问(读/写形式) const type& operator[](size_tp index) const; // 下标访问(只读形式) array& operator=(const array& rhs); // 赋值,改变大小/内容 size_tp get_size() const; // 获得数组大小 void resize(size_tp size); // 重设数组大小,若改小,则丢弃尾数据 void push_back(const type& value); // 追加一个数组元素,数组大小增一 private: void copy(const type *p_source, type *p_target, size_tp size); size_tp _size; type *_arr; }; template <typename type> array <type> ::array(size_tp size, type t): _size(size), _arr(size ? new type[size] : 0) { for (size_tp i = 0; i < size; ++i) // not EXECuted if (size == 0) _arr[i] = t; } template <typename type> array <type> ::array(const array& array): _size(array._size), _arr(array._size ? new type[array._size] : 0) { copy(_array._arr, _arr, array._size); // do nothing if (array._size == 0) } template <typename type> array <type> ::~array() { delete[] _arr; } template <typename type> array <type> & array <type> ::operator=(const array <type> & rhs) { if (&rhs != this) { resize(rhs._size); copy(rhs._arr, _arr, _size); } return *this; } template <typename type> type& array <type> ::operator[](size_tp index) { if (index > = _size) throw( "array::out of range "); return _arr[index]; } template <typename type> const type& array <type> ::operator[](size_tp index) const { if (index > = _size) throw( "array::out of range "); return _arr[index]; } template <typename type> array <type> ::size_tp array <type> ::get_size() const { return _size; } template <typename type> void array <type> ::copy(const type *p_source, type *p_target, size_tp size) { for (size_tp i = 0; i < size; ++i) // not EXECuted if (size == 0) p_target[i] = p_source[i]; } template <typename type> void array <type> ::resize(size_tp new_size) { if (new_size) { type *p = new type[new_size]; copy(_arr, p, _size < new_size ? _size : new_size); delete[] _arr; _arr = p; } else { delete[] _arr; _arr = 0; } _size = new_size; } template <typename type> void array <type> ::push_back(const type& value) { resize(_size + 1); _arr[_size - 1] = value; } int main() // 主测试函数 { array <int> a(30, 5); array <int> b; b.push_back(20); b.push_back(100); a = b; for (array <int> ::size_tp i = 0; i < a.get_size(); ++i) std::cout < < a[i] < < std::endl; return 0; } | | |
|