13

I'm new to overloading operators, I did some search and found this helpful article, I wrote my own code like the author did but I get vector vector::operator*(float, vector) must take either zero or one argument error.

Here is my code:

class vector
{
      public:
       float x;
       float y;

      vector(float, float);
      float operator$ (vector, vector);
      vector operator* (float, vector);
      vector operator* (vector, float);
};

vector::vector(float _x = 0, float _y = 0)
{
   x = _x;
   y = _y;     
}
const float vector::operator$ (const vector &v1, const vector &v2)
{
    return (v1.x * v2.x) + (v1.y * v2.y);
}

const vector vector::operator* (const float &m, const vector &v)
{
    vector ret_val = v;
    ret_val.x *= m;
    ret_val.y *= m;
    return ret_val;
}

const vector vector::operator* (const vector &v, const float &m)
{
      return m * vector;     
} 

My operating system is kubuntu 12.04 and my IDE is dev-C++ running on linux using wine windows program loader.

Cyclonecode
  • 27,619
  • 11
  • 71
  • 89
Mohammad Jafar Mashhadi
  • 3,832
  • 3
  • 29
  • 49

2 Answers2

22

Because you are defining operator*() as a member function, there is already one implicit parameter: the object for which the method is invoked! Therefore, member functions take one explicit parameter, not two.

chrisaycock
  • 34,416
  • 14
  • 83
  • 119
11

Just declare your operator overload function outside the class. Also you are returning a const which might not be what you want.

class foo {
  //code
};

foo operator*(foo& lhs, bar& rhs) const;
foo operator*(bar& lhs, foo& rhs) const;
ajp013
  • 153
  • 1
  • 6
  • why declare the operator overload function outside of the class? – user2131316 Sep 19 '13 at 09:24
  • 2
    This links explains the reason. Hope it helps. http://stackoverflow.com/questions/4652932/why-define-operator-or-outside-a-class-and-how-to-do-it-properly – ajp013 Dec 05 '13 at 16:33