2

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*' 
Community
  • 1
  • 1
Nam Ngo
  • 1,983
  • 1
  • 22
  • 29
  • Look at my (virtually identical) question: http://stackoverflow.com/questions/7651954/overloading-operator-order – Blender Nov 13 '11 at 07:25

2 Answers2

5

Write a free function, like this:

Point operator *(float scale, Point p)
{
    return p * scale;
}
Benjamin Lindley
  • 98,924
  • 9
  • 191
  • 266
4

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; 
Alok Save
  • 196,531
  • 48
  • 417
  • 525