再談[]運算子的重載和二維數組類的[][]運算子多載 —- [][]運算子多載的另一種實現方法

來源:互聯網
上載者:User

關於[][]運算子的重載,已經談了兩篇文章了,本來以為可以做個了結了,卻沒有了結,於是有了這第三篇。前幾天與朋友交流的時候,朋友說她也寫了一個代碼來解決同樣的問題,並且把代碼發給我了,我細細一看,實現原理同我的一樣,但是實現手法和我不同,算是異曲同工了。現把代碼列出如下:

編譯環境:VC++6.0    工程類型:Windows控制台程式

-----------------------------------------------------------------------------------------

// operator overload 3.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "windows.h"

class CData  //儲存資料的類。
{
private:
 WORD *m_data; 
 int m_row,m_column; //行數、列數
public:
 int row_index;      //當前行號
 CData()
 {
  m_data=NULL;
 };
 SetSize(int row, int column)
 {
  if (m_data!=NULL)
  {
   delete[] m_data;
   m_data=NULL;
  }
  m_data=new WORD[row * column];
  m_row=row;
  m_column=column;
  row_index = 0;
 };
 ~CData()
 {
  if (m_data!=NULL)
  {
   delete[] m_data;
   m_data=NULL;
  }
 };
 WORD& operator[]( int Index)
 {
  return m_data[row_index * m_column + Index];
 }; // subscript operator
 WORD *GetBuffer()
 {
  return m_data;
 };
};

class C2DimWordArr   //二維WORD數組類。
{
private:
 int m_row,m_column;        //行數、列數
 CData Array;
public :
 SetSize(int row , int column)
 {
  Array.SetSize(row,column);
  m_row=row;
  m_column = column;
 };
 CData& operator[]( int Index)
 {
  Array.row_index = Index;//記錄當前行號
  return Array;
 };
 WORD *GetBuffer()
 {
  return Array.GetBuffer();
 };
};

int main(int argc, char* argv[])
{
 printf("Hello World!/n");

 C2DimWordArr cwa;

 cwa.SetSize(3,5);  //設定數組大小:3行5列。
 
 long i,j;

 for (i=0;i<3;i++)  //遍曆行
  for (j=0;j<5;j++) //遍曆列
   cwa[i][j]=i*10+j;  //給每個元素賦值

 
 for (i=0;i<3;i++)
  for (j=0;j<5;j++)
   printf("cwa[%d][%d] = %d /n" ,i,j, cwa[i][j]); //列印出每個元素

 //一個元素運算的小實驗。
 printf("cwa[1][0]*cwa[1][2] + cwa[2][1] = %d /n" , cwa[1][0]*cwa[1][2] + cwa[2][1]); //列印出每個元素
 
 //和C/C++標準數組互轉資料的小實驗
 WORD a[3][5];
 memcpy(a, cwa.GetBuffer(),3*5*sizeof(WORD));
 
 for (i=0;i<3;i++)
  for (j=0;j<5;j++)
   printf("a[%d][%d] = %d /n" ,i,j, a[i][j]); //列印出每個元素

 return 0;
}

-----------------------------------------------------------------------------------------

本方法的優點是:由於採用了一維的一個緩衝區來儲存所有的二維資料,因此儲存方式其實和VC的標準二維數組的儲存結構是完全相容的,只消一個memcpy就可以和標準二維數組互拷資料。另外就是,比前兩篇文章中的代碼更加節約記憶體,前兩篇文章中的代碼,二維數組的每一行都用了一個類來表示,因此如果使用者使用的是行多列少的二維數組,那麼記憶體的使用就不是很經濟了。當然總的來說,兩種實現手法各有長處,具體哪種好,要看使用環境,跟要解決的問題有關。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.