重載多維陣列下標 c++

來源:互聯網
上載者:User

其實就是兩個[]疊加起來,具體怎麼實現看代碼。

#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 />

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.