I have class CMatrix, where is "double pointer" to array of values.
class CMatrix {
public:
int rows, cols;
int **arr;
};
I simply need to access the values of matrix by typing:
CMatrix x;
x[0][0] = 23;
I know how to do that using:
x(0,0) = 23;
But I really need to do that the other way. Can anyone help me with that? Please?
Thank you guys for help at the end I did it this way...
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];
}
....
Thank you for your help I really appreciate it!
Rules for Operator OverloadingExisting operators can only be overloaded, but the new operators cannot be overloaded. The overloaded operator contains atleast one operand of the user-defined data type.
In the following example, a class called complx is defined to model complex numbers, and the + (plus) operator is redefined in this class to add two complex numbers. where () is the function call operator and [] is the subscript operator. You cannot overload the following operators: .
RE your edits: No, you can't. There is no such thing as operator overloading in C. You cannot define custom operators to work with your structs, in any way, at all, in C. Operator overloading is something you do in C++, it has nothing what so ever to do with C.
No, C doesn't support any form of overloading (unless you count the fact that the built-in operators are overloaded already, to be a form of overloading). printf works using a feature called varargs.
You cannot overload operator [][]
, but the common idiom here is using a proxy class, i.e. overload operator []
to return an instance of different class which has operator []
overloaded. For example:
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;
};
If you create a matrix using Standard Library containers, it's trivial:
class Matrix {
vector<vector<int>> data;
public:
vector<int>& operator[] (size_t i) { return data[i]; }
};
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