Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ operator overloading order [duplicate]

Possible Duplicate:
Operator Overloading in C++ as int + obj

I override the * operator as following:

Point Point::operator *(float scale){
    Point point(this->x*scale, this->y*scale);
    return point;
}

How can I fix this:

Point p1 (5.0, 10.0);
Point p2 = p1*4; //works fine
Point p3 = 4*p1  //error: no match for 'operator*' 
like image 739
Nam Ngo Avatar asked May 08 '26 15:05

Nam Ngo


2 Answers

Write a free function, like this:

Point operator *(float scale, Point p)
{
    return p * scale;
}
like image 73
Benjamin Lindley Avatar answered May 11 '26 04:05

Benjamin Lindley


You overload the operator as a free function and provide both the versions of it instead of overloading it as member function.

Point operator *(float scale, Point p);
Point operator *(Point p, float scale);

With these:

1st version supports:

Point p3 = 4*p1;

and 2nd version supports:

Point p2 = p1*4; 
like image 36
Alok Save Avatar answered May 11 '26 03:05

Alok Save