Hi!

I have this code, classes with matrices, overloading operator etc (this is just one part, I reduced it from original).

#include<iostream>
using namespace std;

class matrix
{
    protected:
        float* M;
        size_t m,n;
    public:
        matrix(){}
        matrix(size_t m,size_t n);
        matrix(const matrix& A);
        ~matrix();

        matrix& operator=(const matrix& A);
        matrix operator+(const matrix& A) const;

        float& operator[](int i);
};

matrix::matrix(size_t m,size_t n)
{
    this->m=m;
    this->n=n;
    M=new float[m*n];
    for(int i=0;i<m*n;i++)
        M[i]=i;
}

matrix::matrix(const matrix& A)
{
    *this=A;
}

matrix::~matrix()
{
    //delete[] M;
}

matrix& matrix::operator=(const matrix& A)
{
    delete[] M;
    M=new float[A.m*A.n];
    m=A.m;
    n=A.n;
    for(int i=0;i<m*n;i++)
        M[i]=A.M[i];
}

matrix matrix::operator+(const matrix& A) const
{
    if(m==A.m && n==A.n)
    {
        matrix rez(m,n);
        for(int i=0;i<m*n;i++)
            rez[i]=M[i]+A[i];
        return rez;
    }
    else
        cout << "Matrices aren't similar!";
}

float& matrix::operator[](int i)
{
    return M[i];
}

int main()
{
    matrix M1(20,10);
    matrix M2(20,10);
    matrix M3(20,10);

    M3=M1+M2;


    return 1;
}

Im getting this error: error: passing 'const matrix' as 'this' argument of 'float& matrix::operator' discards qualifiers [-fpermissive]. (problem with rez[i]=M[i]+A[i];)
Thanks for your help.

Edited 2 Years Ago by ivan3510

You need to provide both a const and non-const version of your operator[], as so:

class matrix
{
  //..

    float& operator[](int i);
    float operator[](int i) const;
};

//..

float& matrix::operator[](int i)
{
    return M[i];
}

float matrix::operator[](int i) const
{
    return M[i];
}

//..
This article has been dead for over six months. Start a new discussion instead.