Reputation: 4648
I've been thinking this through and didn't come up with anything useful. I have matrix represented by 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 is a container for rows of the matrix (CMatrixRow). I need to throw an exception when someone tries to access matrix outside it's boundaries or in other words one of the used indexes is bigger than the size of the matrix. Problem is, I need to somehow pass the first index into the method
double operator [] (const int index) const;
so it can throw exception with information about both indexes, regardless of which one of them is wrong. I also want to keep it as simple as possible. Can you think of anything?
Upvotes: 0
Views: 680
Reputation: 4648
Eventualy I managed to do it like this
class CMatrix {
public:
double ** matrix;
int height, width, throwFirstIndex;
class Proxy {
public:
Proxy(double * array, const int width, const int rowIndex, bool fail = false);
double & operator [] (const int &index) const;
private:
double * row;
int width, rowIndex;
bool fail;
};
CMatrix(const int &height, const int &width);
CMatrix(const CMatrix &other);
~CMatrix();
Proxy operator [] (const int &index) const;
...
};
I basicaly copied this: Operator[][] overload
Upvotes: 0
Reputation: 110668
Your CMatrixRow
needs to be able to find out which row it is in your container. One easy way to do that is to give CMatrixRow
's constructor an extra parameter that is its row index, which it can then hold on to after it is created. However, this is a form of redundancy and can lead to problems if you start moving CMatrixRow
s around.
It is common to implement matrix access with operator()
taking two arguments instead of having this operator[]
with a helper class. So instead of matrix[i][j]
, you would do matrix(i, j)
. This makes your problem much easier and might also result in a performance increase. See "Why shouldn't my Matrix class's interface look like an array-of-array?" for more information.
Upvotes: 1