I want to implement a matrix class that use operator [][] .
I wrote the below code but the problem is that I cant send const value to operator+ !!(error: passing 'const Matrix' as 'this' argument of 'Matrix::Indexer Matrix::operator' discards qualifiers [-fpermissive])
If I change it to Matrix operator+(Matrix& other); It works fine...
I think I need two overload of Matrix::Indexer Matrix::operator[](int index) one for reading and one for writing to mat_ (like property in c# !) But how ?!
or may be I should use const_cast ?!
What is the best way to implement this class ?!
//Matrix.h
class Matrix
{
public:
Matrix(const int rows, const int cols, float defaultValue=0);
//TODO copy constructor , destructor
int rows() const;
int cols() const;
Matrix operator+(const Matrix& other);
class Indexer
{
public:
Indexer(float* arr,int cols);
float& operator[](int index);
private:
float* arr_;
int cols_;
};
Indexer operator[](int index);
private:
int rows_;
int cols_;
float **mat_;
};
Matrix.cpp
#include "matrix.h"
Matrix::Matrix(const int rows, const int cols, float defaultValue) :
rows_(rows),
cols_(cols)
{
mat_=new float*[rows_];
for(int i=0;i<rows;i++)
{
mat_[i]=new float[cols];
}
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
mat_[i][j]=defaultValue;
}
}
}
int Matrix::rows() const
{
return rows_;
}
int Matrix::cols() const
{
return cols_;
}
Matrix::Indexer::Indexer(float* arr,int cols):
arr_(arr),
cols_(cols)
{}
Matrix::Indexer Matrix::operator[](int index)
{
if(index>=rows_)
throw "Out of row index";
return Indexer(mat_[index],cols_);
}
float& Matrix::Indexer::operator[](int index)
{
if(index>=cols_)
throw "Out of cols index";
return arr_[index];
}
Matrix Matrix::operator+(const Matrix& other)//error
{
if(other.rows()!=this->rows()||other.cols()!=this->cols())
throw "rows and cols are not equal";
Matrix result(other.rows(),other.cols());
for(int i=0;i<rows();i++)
{
for(int j=0;j<cols();j++)
{
result[i][j]=mat_[i][j]+other[i][j];//error: passing 'const Matrix' as 'this' argument of 'Matrix::Indexer Matrix::operator' discards qualifiers [-fpermissive
}
}
return result;
}
[]on a matrix returns aRow, which doesn't contain any data in itself, but presents a view of a subset of the matrix data. (We also have a column view, but this can be tricky to implement.) - James KanzeRowandColumnprovide views (projections) of the matrix. - James Kanze