Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Operator Overloading in expression

I'm sure this has already been answered somewhere, but I don't know what to search for.

I have the following situation. I made a Vector class and overloaded the "*" (multiply by escalar) and the "+" operators (add two vectors). Now, the following line of code:

Vector sum = (e_x*u_c) + (e_y*u_r);

This gives me the following error:

error: no match for 'operator+' in '((Teste*)this)->Teste::e_x.Vector::operator*(u_c) + ((Teste*)this)->Teste::e_y.Vector::operator*(u_r)'

But, if I replace this error line by:

Vector aux = (e_x*u_c);
Vector aux2 = (e_y*u_r);
Vector sum = aux + aux2;

I get no errors at all. Why? Aren't those two expressions meant to be equivalent?

EDIT: Here are my the definitions of "*" and "+":]

Vector Vector::operator+(Vector& right)
{
    return Vector(x + right.x, y + right.y, z + right.z);
}
double Vector::operator*(Vector& right)
{
    return this->scalar_product(right);
}
like image 970
SCHUMMI_IS_BACK_Canada2011 Avatar asked Dec 22 '22 12:12

SCHUMMI_IS_BACK_Canada2011


1 Answers

Replace Vector& right with const Vector& right.

The expression (e_x*u_c) is an rvalue, and references to non-const won't bind to rvalues.

Also, the member functions themselves should be marked const as well:

Vector Vector::operator+(const Vector& right) const
{
    return Vector(x + right.x, y + right.y, z + right.z);
}

double Vector::operator*(const Vector& right) const
{
    return this->scalar_product(right);
}

scalar_product will also have to be marked const. Read more about const correctness here.

like image 157
fredoverflow Avatar answered Jan 14 '23 10:01

fredoverflow