其实就是两个[]叠加起来,具体怎么实现看代码。
http://blog.csdn.net/hityct1/article/details/4123135
- #include <iostream>
- #include <string>
- using namespace std;
- template <class T> class arr;
- template <class T> class arrBody
- {
- private:
- friend class arr<T>;
- T* data;
- int row,col,current_row;
- arrBody(int r,int c,T d):row(r),col(c)
- {
- data=new T[r*c];
- current_row=-1;
- for(int k=0;k<r*c;k++) //初始化数据,默认为0
- data[k]=d;
- }
- public:
- T& operator[](int j) //重载第2个[]号
- {
- if(j>=0&&j<col)
- return data[current_row*col+j];
- }
- ~arrBody(){delete[]data;}
- };
- template <class T> class arr
- {
- private:
- arrBody<T> tBody;
- public:
- arrBody<T> &operator[](int i) //重载第一个[]号
- {
- if(i>=0&&i<tBody.row)
- tBody.current_row=i;
- return tBody;
- }
- arr(int i,int j,T d=0):tBody(i,j,d) {}
- };
- void main()
- {
- arr<int> a(10,20);
- arr<double> b(5,5);
- cout<<a[5][5]<<endl;
- }