namespace dlove{ templateclass ForNextOperator{ //为了实现operator[][]的重载 friend Object; Object *object; Int32 receive1; //第一次接受的operator[]的参数 private: //全部设为 private 是为了防止.. ForNextOperator(Object *_base,Int32 _rece1): object(_base),receive1(_rece1){ ; } public: ForNextOperator(const ForNextOperator &fno): object(fno.object),receive1(fno.receive1){ ; } public: typename Object::value_type& operator[](Int32 _column){ return *(object->base+(object->column*receive1+_column)); //需要重载operator[][]的类需要有表示基址的base,二维数组列数的column } };}
以二维数组演示:
namespace dlove{ templateclass Array2D{ friend ForNextOperator ; public: enum Arribute{ROW,COLUMN}; public: //类型定义,由于 Array2D 不准备与 STL 兼容;所以只定义一些会使用的 typedef ElemType value_type; private: ElemType *base; Int32 row; //行 Int32 column; //列 public: Array2D(Int32 _row,Int32 _column): row(_row),column(_column){ base=new ElemType[row*column](); //分布空间并默认初始化; } Int32 get(Arribute arrib){ switch(arrib){ case ROW:return row; case COLUMN:return column; } return 0; } ForNextOperator operator[](int _row){ return ForNextOperator (this,_row); } };}
测试:
#include#include #include using namespace std;using namespace dlove; #define OUTPUTCONTAINER(container) copy(container.begin(),container.end(),ostream_iterator (cout,"\t"));cout< ::ROW);++ci){\ for(Int32 cj(0);cj ::COLUMN);++cj){\ cout< <<"\t";\ }\ cout< arr2d(3,4); OUTPUT_ARRAY2D; for(Int32 ci(0);ci ::ROW);++ci){ for(Int32 cj(0);cj ::COLUMN);++cj){ arr2d[ci][cj]=randab; } } OUTPUT_ARRAY2D; return EXIT_SUCCESS;}