I'm having a problem to make the code:
void main(){
Matrix c(rows,cols);//rows & cols are int numbers
c[0][0]=2//the line that I'm having a problem to do the operator
}
//My class defined like this:
class Matrix{
public:
Matrix(int rows,int cols): rows(rows), cols(cols){
mat= new double*[cols];
for( int i=0; i<rows;i++){
*mat=new double[i];
}
}
private:
int rows,cols;
double **mat;
};
How can I make an operator that will help me to do the line that I'm having a problem with?
Don't dynamically allocate in two dimensions like that. It's poison for your cache, and completely pointless. I see it all the time and I wish I didn't! Make yourself a nice
std::vector<double>
of sizerows*cols
instead.Anyway, the trick to permit
[width][height]
is a proxy class. Have youroperator[]
return an instance of a class that has its ownoperator[]
to do the second-level lookup.Something like this:
(In reality, you'd want to make it moveable and it could doubtlessly be tidied up a bit.)
Certainly, switching to
operator()
or a.at(width, height)
member function is a lot easier…There are no
operator [][]
, butoperator[]
. So that one should return something for which you can use[]
too (pointer or proxy class).In your case, you might simply do:
For more complicated cases, you have to return a proxy class.