重载 "operator[][]"

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
        }
    };
}

以二维数组演示:

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;
}

 

转载于:https://my.oschina.net/u/1383479/blog/171078

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值