「operator[]」をリロード
2624 ワード
namespace dlove{
template<typename Object>
class 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
}
};
}
2 D配列で表示:
namespace dlove{
template<typename ElemType>
class Array2D{
friend ForNextOperator<Array2D>;
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<Array2D> operator[](int _row){
return ForNextOperator<Array2D>(this,_row);
}
};
}
テスト:
#include<dlove_basic.h>
#include<dlove_Random.h>
#include<dlove_Array2D.h>
using namespace std;
using namespace dlove;
#define OUTPUTCONTAINER(container) copy(container.begin(),container.end(),ostream_iterator<Int32>(cout,"\t"));cout<<endl;
// ;
#define OUTPUT_ARRAY2D \
for(Int32 ci(0);ci<arr2d.get(Array2D<Int32>::ROW);++ci){\
for(Int32 cj(0);cj<arr2d.get(Array2D<Int32>::COLUMN);++cj){\
cout<<arr2d[ci][cj]<<"\t";\
}\
cout<<endl;\
}
int main(){
Randomab randab(-777,777);// [-777,777)
Array2D<Int32> arr2d(3,4);
OUTPUT_ARRAY2D;
for(Int32 ci(0);ci<arr2d.get(Array2D<Int32>::ROW);++ci){
for(Int32 cj(0);cj<arr2d.get(Array2D<Int32>::COLUMN);++cj){
arr2d[ci][cj]=randab;
}
}
OUTPUT_ARRAY2D;
return EXIT_SUCCESS;
}