重载多维数组下标 c++

其实就是两个[]叠加起来,具体怎么实现看代码。

http://blog.csdn.net/hityct1/article/details/4123135

  1. #include <iostream>   
  2. #include <string>  
  3.   
  4. using namespace std;  
  5.   
  6. template <class T> class arr;  
  7. template <class T> class arrBody  
  8. {  
  9.     private:  
  10.     friend class arr<T>;  
  11.     T* data;  
  12.     int row,col,current_row;  
  13.     arrBody(int r,int c,T d):row(r),col(c)  
  14.     {  
  15.         data=new T[r*c];  
  16.         current_row=-1;  
  17.         for(int k=0;k<r*c;k++)              //初始化数据,默认为0  
  18.             data[k]=d;  
  19.     }  
  20.     public:  
  21.         T&   operator[](int  j)            //重载第2个[]号  
  22.         {  
  23.             if(j>=0&&j<col)  
  24.                 return data[current_row*col+j];  
  25.         }  
  26.         ~arrBody(){delete[]data;}     
  27. };  
  28.   
  29. template <class  T>  class arr     
  30. {     
  31. private:  
  32.     arrBody<T> tBody;     
  33. public:     
  34.     arrBody<T>  &operator[](int i)         //重载第一个[]号  
  35.     {  
  36.         if(i>=0&&i<tBody.row)  
  37.             tBody.current_row=i;  
  38.         return tBody;  
  39.     }  
  40.     arr(int  i,int  j,T d=0):tBody(i,j,d) {}     
  41. };  
  42.   
  43.   
  44. void main()  
  45. {  
  46.     arr<int> a(10,20);  
  47.     arr<double> b(5,5);  
  48.     cout<<a[5][5]<<endl;  
  49. }  

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值