#define ROW 3
#define COL 4
class Matrix
{
private:
int mat[ROW][COL];
//.....
//.....
};
int main()
{
Matrix m;
int a = m[0][1]; // reading
m[0][2] = m[1][1]; // writing
}
I think directly it not possible to overload [][] .
I think i have to do it indirectly but how to implement it?
The easier solution is to use the operator() as it allows multiple parameters.
class M
{
public:
int& operator()(int x,int y) {return at(x,y);}
// .. Stuff to hold data and implement at()
};
M a;
a(1,2) = 4;
The easy way is that the first operator[] returns an intermediate object that the second operator[] returns the value from the array.
class M
{
public:
class R
{
private:
friend class M; // Only M can create these objects.
R(M& parent,int row): m_parent(parent),m_row(row) {}
public:
int& operator[](int col) {return m_parent.at(m_row,col);}
private:
M& m_parent;
int m_row;
};
R operator[](int row) {return R(*this,row);}
// .. Stuff to hold data and implement at()
};
M b;
b[1][2] = 3; // This is shorthand for:
R row = b[1];
int& val = row[2];
val = 3;
Since you want to store your elements in fixed-size arrays it'll be fairly easy:
#define ROWS 3
#define COLS 4
typedef int row_type[COLS];
class matrix {
row_type elements[ROWS];
public:
...
row_type const& operator[](int r) const {return elements[r];}
row_type & operator[](int r) {return elements[r];}
...
};
That should work.
In addition, you may want to replace the #define
s with proper constants or use template parameters for type (int) and size (3x4) to make your matrix class more generic. If you want to support dynamic sizes your operator[] needs to return proxy-objects. It's possible but you should probably prefer operator() with two index parameters for element access.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With