[原創]多維陣列下標運算子多載

來源:互聯網
上載者:User

遇到一道筆試題:設計一個矩陣類,行和列數通過建構函式輸入,支援a[][]取值和賦值。
這實際上就是一個二維數組下標運算子多載的問題,解決思路如下:
(1)用一維數組代替二維數組分配記憶體,從而獲得連續的記憶體空間,取值時通過計算獲得相應行和列上的值
(2)設計兩個類,分別重載operator[],一個擷取行,一個擷取列
實現如下:

代碼

class MatrixEntry{
    friend class Matrix; //友元類,訪問私人變數m_currentRow
public:
    MatrixEntry(int m, int n) : m_row(m), m_col(n)
    {
         m_pMatrix = new int[m * n * sizeof(int)];
    }

    ~MatrixEntry()
    {
         delete m_pMatrix;
    }

    int & operator[](int col)
    {
         return m_pMatrix[m_currentRow * m_col + col];
    }

 

private:
    int * m_pMatrix; //儲存矩陣的一維數組
    int m_row;         //矩陣的行數
    int m_col;          //矩陣的列數
    int m_currentRow; //指示當前需要訪問哪一行,該值由下面的Matrix類設定
};

 

class Matrix{
public:
    Matrix(int m, int n) : m_entry(m, n)
    {
    }

    MatrixEntry & operator[](int row)
    {
         m_entry.m_currentRow = row;
         return m_entry;
    }

 

private:
    MatrixEntry m_entry;
};

測試一下:

測試代碼

int x = 1;
int i; 

Matrix m(5, 5);

for(i=0; i<5; i++)
{
    for(int j=0; j<5; j++)
   {
        m[i][j] = x++;
   }
}

for(i=0; i<5; i++)
{
    for(int j=0; j<5; j++)
    {
        cout << m[i][j] << endl;
     }
}

上面的實現只考慮了最基本的功能,沒有涉及下標越界等錯誤處理邏輯,有興趣的朋友可以補全。如果要設計一個泛型類,則把int替換為template<class T>中的T即可。

聯繫我們

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