flo3299 - 2 months ago 16
C++ Question

# Overload operators += and + Matrix c++

I'm having problems with overloading operators += and + in c++. I've got the following and I don't know why.. : "Invalid operands to binary expression (Matrice* and Matrice*) Do you have any ideas why ? Thanks.

NB : operator = does work.

# main.cpp

``````#include <iostream>
#include <cmath>
using namespace std ;
#include "Matrice.hpp"

int main () {

double *tableau = new double[2*2]{1,4,3,2} ;
double *tableau1 = new double[2*2]{1,6,4,-2} ;
Matrice * A = new Matrice(2, tableau) ;
Matrice * B = new Matrice(2, tableau1) ;
Matrice * C = new Matrice() ;

C = A+B ;} // error appears here
``````

# Matrice.cpp

``````#include "Matrice.hpp"

Matrice::Matrice(const Matrice& m) : dim(m.dim), coeffs(new         double[m.dim*m.dim]){
for(int i=0; i<dim*dim; i++) {
coeffs[i] = m.coeffs[i] ;
}

}

Matrice::~Matrice() {
delete [] coeffs ;
}
``````

# Matrice.hpp

``````#ifndef Matrice_hpp
#define Matrice_hpp

#include <iostream>
using namespace std ;

class Matrice {
private :
unsigned int dim;
double * coeffs ;

public :
Matrice() {
dim = 2 ;
coeffs = new double[dim*dim] ;
for(int i=0; i<dim*dim; i++) {
coeffs[i] = 0 ;
}
}

Matrice(unsigned int n, double* v) : dim(n), coeffs(new double[dim*dim]) {
if(v) { for(int i=0; i<dim*dim; i++) { coeffs[i] = v[i] ;}
}
else { for(int i=0; i<dim*dim; i++) coeffs[i] = 0 ; }
}

Matrice(const Matrice&) ;
~Matrice () ;

int dimension() const {return dim;}
void modifier(int position, int valeur) {coeffs[position] = valeur ; }

Matrice& operator= (const Matrice& m) {
if(coeffs != m.coeffs) {
delete [] coeffs ;
dim = m.dim ;
coeffs = new double[m.dim*m.dim] ;
for(int i=0; i<m.dim*m.dim ; i++) {
coeffs[i] = m.coeffs[i] ;
}
}

return *this ;
}

Matrice& operator+=(const Matrice& m) {
for(int i=0; i<dim*dim; i++) {
coeffs[i] += m.coeffs[i] ;
}

return *this ;
}

Matrice&operator+ (const Matrice& m)
{

for(int i=0; i<dim*dim; i++) {
coeffs[i] = coeffs[i] + m.coeffs[i] ;
}
return *this ;
}

double* Coefficients() {return coeffs ;}
void Afficher() {
for(int i=0; i<dim*dim; i++) {
if (i%dim == 0) {cout << endl ; }
cout << coeffs[i] << " "  ;
}
cout << endl ;
}

};

#endif /* Matrice_hpp */
``````

When you define operator in a class it can be used for instance of that class, not pointer. So if you change your code to:

``````Matrice A(2, tableau) ;
Matrice B(2, tableau1) ;
Matrice C = A + B;
``````

it should work. You can also get similar effect dereferencing your pointers:

``````*C = *A + *B;
``````

but there is no reason to use dynamically allocated objects in your code. For example you have memory leaks in your code as you do not have proper cleanup (delete statements).

Source (Stackoverflow)