c++ - Overloading 2D array operator and throwing exception -


i've been thinking through , didn't come useful. have matrix represented 2 classes:

class cmatrix { public:     cmatrixrow * matrix;     int height, width;     cmatrix(const int &height, const int &width);     cmatrix(const cmatrix &other);     ~cmatrix();     cmatrixrow operator [] (const int &index) const;      ... }  class cmatrixrow { public:     int width;     cmatrixrow(const int &width);     cmatrixrow(const cmatrixrow &other);     ~cmatrixrow();     double operator [] (const int index) const;     void operator =(const cmatrixrow &other); private:     double * row; 

};

where cmatrix container rows of matrix (cmatrixrow). need throw exception when tries access matrix outside it's boundaries or in other words 1 of used indexes bigger size of matrix. problem is, need somehow pass first index method

double operator [] (const int index) const; 

so can throw exception information both indexes, regardless of 1 of them wrong. want keep simple possible. can think of anything?

your cmatrixrow needs able find out row in container. 1 easy way give cmatrixrow's constructor parameter row index, can hold on after created. however, form of redundancy , can lead problems if start moving cmatrixrows around.

it common implement matrix access operator() taking 2 arguments instead of having operator[] helper class. instead of matrix[i][j], matrix(i, j). makes problem easier , might result in performance increase. see "why shouldn't matrix class's interface array-of-array?" more information.


Comments