C++的逐层抽象:从结构体到类、模板( 三 )

// array.h#include <iostream.h>// 类模板的友元:重载输入运算符template<class T>class Array;// 类模板Array的声明template<class T>ostream &operator<<(ostream &os, const Array<T>&obj); // 输出重载声明template <class T>class Array {friend ostream &operator<<(ostream &os, const Array<T>&obj);private:int low;int high;T *storage;public:// 根据low和high为数组分配空间 。分配成功,返回值为true,否则返回值为falseArray(int lh = 0, int rh = 0):low(lh),high(rh){storage = new T [high - low + 1];}// 复制构造函数Array(const Array &arr);// 赋值运算符重载函数Array &operator=(const Array & a);// 下标运算符重载函数T & operator[](int index);const T & operator[](int index) const;// 作为右值// 回收数组空间~Array(){if(storage)delete [] storage;}};template <class T>T & Array<T>::operator[](int index){if (index < low || index > high){cout <<"下标越界";return;}return storage[index - low];}template <class T>const T & Array<T>::operator[](int index) const{if (index < low || index > high){cout <<"下标越界";return;}return storage[index - low];}// 类模板的友元:重载输出运算符template<class T>ostream &operator<<(ostream &os, const Array<T>&obj){os << endl;for (int i=0; i < obj.high - obj.low + 1; ++i)os << obj.storage[i] << 't';return os;}template<class T>Array<T>::Array(const Array<T> &arr){low = arr.low;high = arr.high;storage = new T [high - low + 1];for (int i = 0; i < high -low + 1; ++i)storage[i] = arr.storage[i];}template<class T>Array<T> &Array<T>::operator=(const Array<T> & a){if (this == &a)// 防止自己复制自己return *this;delete [] storage;// 归还空间low = a.low;high = a.high;storage = new T[high - low + 1];// 根据新的数组大小重新申请空间for (int i=0; i <= high - low; ++i)storage[i] = a.storage[i];// 复制数组元素return *this;}// main.cpp#include <iostream.h>#include "array.h"int main(){int start, end;cout<<"请输入数组的下标和上标,如1 9:";cin>>start>>end;Array<double> arr(start,end), arr2;for(int i = start ; i<= end-start+1 ; i++)arr[i] = i*0.9;arr[8] = 8.8;arr2 = arr;cout<<arr2<<endl;while(1);return 0;}-End-


【C++的逐层抽象:从结构体到类、模板】


推荐阅读