I am making a program in C++ in which I have to multiply two matrices, however when I create the method operator*
and test it (being empty), it gives me the error that it puts in the title:
main.cpp:28:20: error: invalid operands of types ‘matrix<float>*’ and ‘matrix<float>*’ to binary ‘operator*’
matrix<float>* b=a*a;
~^~
What I have in the main is the following:
#include <iostream>
#include <exception>
using namespace std;
#include "excepciones.hpp"
#include "matrix.cpp"
int main (){
matrix<float>* a;
int x=0, y=0;
cout<<"introduzca el numero de filas de la matriz:"<<endl;
cin>> x;
cout<<"introduzca el numero de columnas de la matriz:"<<endl;
cin>>y;
try{
a=new matrix<float> (x,y);
}
catch(exception& e){
cout<<e.what()<<endl;
}
matrix<float>* b=a*a;
}
and the operator* method is as follows:
template <class T>
matrix<T>* matrix<T>::operator*(matrix<T>* a){
return NULL;
}
In hpp it is defined as follows:
matrix<T>* operator*(matrix<T>* a);
It shouldn't work, because the type of object to be multiplied is specified in the method, (being fine), and for now, it returns NULL
, which is a value that the pointer b
can accept without problems
The error is clear and concise, you may not understand it because it is in English, I will translate it for you:
The compiler is marking the expression
b=a*a
as the source of the error, what are the types of the variables involved?The variable
a
has been defined as a pointer (*
) to the templatematrix
instantiated with typefloat
:The variable
b
has been defined as a pointer (*
) to the templatematrix
instantiated with typefloat
:Now let's see how your multiplication operator is defined:
The multiplication operator is defined as a member function that receives a pointer parameter (
*
) to the templatematrix
instantiated with typeT
. Since it is a member function, to the left of the (multiplication) operator there must always be an instance ofmatrix
but you don't have an instance ofmatrix
you have pointers!:It will work for you if you de-reference the left operand pointer:
But this is nonsense, the design is completely inadequate:
*=
) the function should be constant or should be outside the operated class.Taking into account the previous points, your operator should be like this:
Or even better, like this:
With either option, your function
main
should look like this:The compiler throws the error because the first element of the product cannot be a pointer. Put another way, the operator overloading is done for an object of type
matrix<T>
and not for a pointer tomatrix<T>
.The following examples should fix the error: