其實就是兩個[]疊加起來,具體怎麼實現看代碼。
#include <iostream><br />#include <string></p><p>using namespace std;</p><p>template <class T> class arr;<br />template <class T> class arrBody<br />{<br /> private:<br /> friend class arr<T>;<br /> T* data;<br /> int row,col,current_row;<br /> arrBody(int r,int c,T d):row(r),col(c)<br /> {<br /> data=new T[r*c];<br /> current_row=-1;<br /> for(int k=0;k<r*c;k++) //初始化資料,預設為0<br /> data[k]=d;<br /> }<br /> public:<br /> T& operator[](int j) //重載第2個[]號<br /> {<br /> if(j>=0&&j<col)<br /> return data[current_row*col+j];<br /> }<br /> ~arrBody(){delete[]data;}<br />};</p><p>template <class T> class arr<br />{<br />private:<br /> arrBody<T> tBody;<br />public:<br /> arrBody<T> &operator[](int i) //重載第一個[]號<br /> {<br /> if(i>=0&&i<tBody.row)<br /> tBody.current_row=i;<br /> return tBody;<br /> }<br /> arr(int i,int j,T d=0):tBody(i,j,d) {}<br />};</p><p>void main()<br />{<br /> arr<int> a(10,20);<br /> arr<double> b(5,5);<br /> cout<<a[5][5]<<endl;<br />}<br />