2013-04-02 72 views
11

我有類CMatrix,其中是對數組數組的「雙指針」。C++過載運算符[] []

class CMatrix { 
public: 
    int rows, cols; 
    int **arr; 
}; 

我只需要鍵入訪問矩陣的值:

CMatrix x; 
x[0][0] = 23; 

我知道那是用做:

x(0,0) = 23; 

但我真的需要做,其他辦法。任何人都可以幫助我嗎?請?

謝謝你們在我到底做了這樣的幫助...

class CMatrix { 
public: 
    int rows, cols; 
    int **arr; 

public: 
    int const* operator[](int const y) const 
    { 
     return &arr[0][y]; 
    } 

    int* operator[](int const y) 
    { 
     return &arr[0][y]; 
    } 

    .... 

謝謝您的幫助,我真的很感激!

+4

沒有'運營商[] []'的'C++',你不能讓一個... –

+0

「我真的需要這樣做」,爲什麼?這是一項任務嗎? –

+0

只是超載數組項目的[]操作符 –

回答

17

C++中沒有operator[][]。但是,您可以重載operator[]來返回另一個結構,並且在那個過載operator[]也得到您想要的效果。

1

你可以operator[]並讓它返回一個指向矩陣各自的row or column的指針。 由於指針支持[]的下標,因此可以通過'雙方'notation [][]訪問。

3

您可以通過重載operator[]返回int*,然後由[]的第二個應用程序索引。代替int*,您也可以返回另一個表示行的類,它的operator[]可以訪問該行的各個元素。

本質上,operator []的後續應用程序對前一個應用程序的結果起作用。

21

你不能重載operator [][],但這裏的習慣用法是使用代理類,即超載operator []返回不同的類,它具有operator []重載的一個實例。例如:

class CMatrix { 
public: 
    class CRow { 
     friend class CMatrix; 
    public: 
     int& operator[](int col) 
     { 
      return parent.arr[row][col]; 
     } 
    private: 
     CRow(CMatrix &parent_, int row_) : 
      parent(parent_), 
      row(row_) 
     {} 

     CMatrix& parent; 
     int row; 
    }; 

    CRow operator[](int row) 
    { 
     return CRow(*this, row); 
    } 
private: 
    int rows, cols; 
    int **arr; 
}; 
+0

您可能希望將'CMatrix'類設置爲'CRow'類的'friend',或者它將無法構建「CRow」。 –

1

如果您在使用標準庫的容器創建一個矩陣,是微不足道:

class Matrix { 
    vector<vector<int>> data; 

public: 
    vector<int>& operator[] (size_t i) { return data[i]; } 
}; 
+0

,因爲這是學校作業我不能使用任何其他庫感謝iostream :( –

+1

這是沒有說明問題的要求。 –